Click to See Complete Forum and Search --> : questions about default constructor
nsly
August 6th, 2003, 05:02 AM
//baseClass.h
class baseClass {
public:
baseClass() {};
}
//derivedClass
class derivedClass : public baseClass {
public:
derivedClass() {};
...other function and members
}
but the question is why complier (vs.net) tell me that error C2512: derivedClass: no appropriate default constructor available, when I try to declare like this:
baseClass bc = new derivedClass();
shall I say that an empty constructor expicitly defined by user is not the way to do this?
Paul McKenzie
August 6th, 2003, 05:13 AM
Originally posted by nsly
but the question is why complier (vs.net) tell me that error C2512: derivedClass: no appropriate default constructor available, when I try to declare like this:
baseClass bc = new derivedClass();
There are two problems with your code:
1) Operator new returns a pointer to an object, not an object.
baseClass *bc = new derivedClass();
2) Even if you did declare a pointer, your code is ill-formed. Your baseClass must have a virtual destructor. If not, deleting the *bc object invokes undefined behavior.
Regards,
Paul McKenzie
nsly
August 6th, 2003, 05:20 AM
if I remove all the empty ctor I created (because I don't have anyting to do within the ctor), I still got that error.
but what I assume is the compiler Must create one default for me.
so could I initiate one instance of the class using new (like baseClass bc = new derivedClass(); )?
Graham
August 6th, 2003, 05:23 AM
Read what Paul said: new returns a pointer and you are declaring an object. When you put
baseclass b = new derived;
you are trying to invoke the constructor baseclass::baseclass(derived*), which doesn't exist.
nsly
August 6th, 2003, 05:23 AM
sorry for wrong typing.
yes u r right, I do use pointer. baseClass * bc = new derivedClass();
the second problem is not really related to my question, even though I know this is. (that code is just a example).
Andreas Masur
August 6th, 2003, 07:13 AM
[Moved thread]
codeguru.com
Copyright WebMediaBrands Inc., All Rights Reserved.