This is the code I'm trying to understand. It has no specific use. I'm just trying to understand what happens.
#include<iostream>
using namespace std;
class derivedClass;
class baseClass
{
public:
int objID;
derivedClass* dcObjPtr;
baseClass()
{
cout << "(1) Default constructor" << objID << endl;
}
baseClass(int ID)
{
objID = ID;
dcObjPtr = new derivedClass(1);
cout << "(2) Constructing base object with ID: " << objID << endl;
}
};
class derivedClass : public baseClass
{
public:
derivedClass()
{}
derivedClass(int ID) : baseClass(ID)
{
cout << "(4) Constructing derived object with ID: " << objID << endl;
}
};
int main(int argc, char** argv)
{
derivedClass dcObj(1);
return 0;
}
Using VS2013 I get the error "derivedClass: class has no constructors", which I don't think is the right error.
I was first using a derivedClass instance, not a pointer. And that was giving me a weird error about a semicolon. Then I saw this post where the accepted answer was to have a pointer, instead of an instance.
These are the questions I have:
- Why is the compiler complaining about no constructors. The class clearly has constructors.
- How would this work? When we create an instance of dervedClass, there is a baseClass part in it. And this baseClass part has a derivedClass in it, and so on. This is recursive. I would assume if it works it would result in a segmentation fault or something like that. Am I right to assume that this would be recursive (if it works)?
Cheers.