class A{
A();
~A();
virtualvoid printstuff(){cout << "A::printstuff" << endl;
....... };
class B: public A{
B();
~B();
void printstuff(){cout << "B::printstuff"<< endl;
......};
int main() {
......
A* b2 = new B();
b2->printstuff();
}
What does A* b2 = new B() actually mean? I would guess it means create an object of attribute A which points to B? Why is it also that it prints out A::printstuff of class A? I understand a little of polymorphism but I just do not get how A* b2 = new B(); relates to that. Can anyone explain that certain line of code?
Thanks for the correction I am so so sorry, the format was a bit off so I probably removed some lines without noticing. Just curious is it ok to write constructors just as A(); rather A() {}; ?
You have to supply a body for the constructor somewhere. You can write A(); but then you need a body for the constructor in your .cpp file. By specifying A() {} in your header file, you're specifying the constructor is empty.
The constructor that takes no arguments is the default constructor.
If you don't put it into the class at all, then the compiler will add it for you, except if the class has some other constructor.
You can still explicitly declare the default constructor and ask the compiler to generate its implementation: