Archived

This topic is now archived and is closed to further replies.

Can you call classes own constructor?

This topic is 4946 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, i just ran in to a tricky problem. This code below doesnt set the three vars to zero like i asumed, so is there any other ways?
class B
{
public:
 B():
	{
		d = 0;
		e = 0;
		f = 0;
	}
	B(int a)
	{
  B(); // doesnt call????

	}
	int d,e,f;
};

int main()
{

B b; // d,e, and f doesnt change to zero


return 1;
}

Share this post


Link to post
Share on other sites
How about:


class B
{
public:
B(): d(0),e(0),f(0) {} //<-- Constructor Initializers

private:
int d,e,f;
};


If you'd like, you can google "constructor initializers" and you'll find helpful examples.

[edited by - nervo on May 29, 2004 12:12:38 AM]

Share this post


Link to post
Share on other sites
If I remember correctly, yes you can call a class' own constructor.

Just change

B();

to

B::B();

I use this technique for a few of my constructors as well. (With inheritance , for example).

[edited by - Just3D on May 29, 2004 12:17:28 AM]

[edited by - Just3D on May 29, 2004 12:18:12 AM]

Share this post


Link to post
Share on other sites
No. B() will create (and here discard) a temporary object. What Just3D is referring to works only for passing arguments to parent classes in inheritance hierarchies, and only in the initializer list, not the constructor body.

Share this post


Link to post
Share on other sites
Wow! I just tested that with Builder, and you''re right, Miserable!

Nevermind what I said Craazer, the method I used only works when the constructor is inherited.

I guess you learn something new everyday.

Share this post


Link to post
Share on other sites
quote:
Original post by Zipster
The solution to your problem is to create a special initialization function you call in both constructors.



Thats what I''ve been doing so far, and will keep using it then, I quess.

Thanks though!

Share this post


Link to post
Share on other sites