Skip to main content
GameDev.net gamedev.net
🔒 Locked

Class default contructor

Started by vbisme Mar 11, 2005 at 1:21 PM 5 replies 1.3k views
Original Post
vbisme
vbisme
Let's say you have a class with no default constructor: class A { public: A( int ID ); //Some other stuff }; Then you try to contain it in another class: class B { private: A m_myA; //this won't compile }; Is there a solution to this without specifying a default constructor in class A?
Evil Steve
Evil Steve
Yup, this is one of the manu uses for initializer lists:
class B{   B() : m_myA(42) {} // Replace 42 with whatever you want   B(int nID) : m_myA(nID) {} // Alternate version, delegate the value passed to the constructorprivate:   A m_myA; //this won't compile};
Zahlman
Zahlman
To construct a derived object, you must be able to construct its base first, given the derived constructor args. If you do not specify what construction to use, the default is used - and as you've seen, if there's no default constructor, no compilation for you.

The initializer list is where you specify the exact construction process to use, as in Evil Steve's example (which should now compile despite the comment :) ). By the time you get to the constructor body it is too late, and there's no syntax within it anyway.

Initializer lists are your friends; you should be using them to initialize other data members where possible, too.
Evil Steve
Evil Steve
Quote:
Original post by Zahlman
...which should now compile despite the comment :)...
Whoops... Peh, I can't be bothered editing it again...
vbisme
vbisme
What if class B needs to initialize an object after it's constructor and then use that object to initialize object A. As mentioned, by the time we get to the constructor's body it's too late.
Fruny
Fruny
Quote:
Original post by vbisme
What if class B needs to initialize an object after it's constructor and then use that object to initialize object A. As mentioned, by the time we get to the constructor's body it's too late.


Pointers and dynamic allocation.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Evil Steve
Evil Steve
Quote:
Original post by Fruny
Pointers and dynamic allocation.
To expand on that slightly - You have 2 choices - Pointers and dynamic allocation, or making the subclass not take any parameters to its constructor. If you go for dynamic allocation (I.e. using new and delete) you can choose when to allocate memory for, and construct the child object.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.