Hello friends ........
it's ma first post.
As i know, constructors are called at the time of object creation.
But if i want to call it explicitly, not at time of object creation, can i do this?
if yes?
then how?
any help please?.........
Hello friends ........
it's ma first post.
As i know, constructors are called at the time of object creation.
But if i want to call it explicitly, not at time of object creation, can i do this?
if yes?
then how?
any help please?.........
Yes, you can do. It is used to create Temporary object.
class One{
public:
One() {
cout << "\nConstructor";
}
~One(){
cout << "\nDestructor";
}
};
int main(){
One a;
One(); // Temp object
return 0;
}
Although Adatapost's solution will compile and work, there's no reason why you should use this (ever).
I would choose for an init-function that's called from the constructor. You can always call this function at a different time:
class foo{
public:
foo(){init();};
~foo(){};
void init(void);
};
void foo::init(){
std::cout << "Init called\n";
}
int main(void)
{
foo f;
f.init();
return 0;
}
Although Adatapost's solution will compile and work, there's no reason why you should use this (ever).
Well Adatapost's specific example doesn't achieve much but there's still a reason to do that. e.g. in constructing a temporary object to pass to a function:-
class Point
{
Point(int x1, int y1){x = x1; y = y1;}
int x;
int y;
};
int main(){
int distance = GetDistance(Point(2,3),Point(4,6));
return 0;
}
Calling an 'init' function is a different thing altogether, and more useful to the OP, since I think he wanted to know whether the constructor could be called on an existing object. The answer to that is that constructors cannot be called in the normal way, only by mechanisms such as 'new', declaration etc.
However I think the OP was actually
but there's still a reason to do that. e.g. in constructing a temporary object to pass to a function:-
I would still prefer an init() function:
class Point
{
public:
Point(int x1, int y1){init(x1,y1);}
void init(int, int);
int getSomething(void);
private:
int x;
int y;
};
void Point::init(int x1, int y1){
x = x1;
y = y1;
}
int Point::getSomething(){
return x+y;
}
int main(){
Point p(2,3);
std::cout << p.getSomething() << '\n';
p.init(4,5);
std::cout << p.getSomething() << '\n';
return 0;
}
However I think the OP was actually
Was actually what? ;)
thanks all of you ....
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.