Jump to content
  • Advertisement

Archived

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

PHRICTION

Calling constructors from other constructors

This topic is 5560 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

Is it alright to do something like this?
class SomeClass
{
public:
//...blah, blah, blah

SomeClass();
SomeClass( int parameter );

};


SomeClass::SomeClass()
{
//Set up some data here

}

SomeClass::SomeClass( int parameter )
{
//Is it alright to call the other constructor??

SomeClass();
//...do something with parameter


}

Share this post


Link to post
Share on other sites
Advertisement
That doesn''t do what you think it does. It creates a temporary variable of type SomeClass and immediately destroys it. The original object is unaffected.


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
What he said. The recommended thing to do in this situation is write another function, say "Init", and have both constructors just call "Init", and then have the overloaded constructor do what else it needs to.

Share this post


Link to post
Share on other sites
I see. Thank you for the quick response guys. This explains alot, yet is somewhat disapointing. It seems like it would be really conveiniant to be able to do that. Oh well.

Share this post


Link to post
Share on other sites
quote:
Original post by PHRICTION
I see. Thank you for the quick response guys. This explains alot, yet is somewhat disapointing. It seems like it would be really conveiniant to be able to do that. Oh well.

In practice, you can get something similar to this with default arguments. Like so:

class Point
{
public:
Point(double x = 0.0, double y = 0.0) : x(x), y(y) { }
private:
double x,y;
};

Presto! an implicit default constructor!


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!