#include<iostream>
using namespace std;
class base {
public:
base() {
cout<<"Constructing base \n";
}
virtual ~base() {
cout<<"Destructing base \n";
}
};
class derived: public base {
public:
derived() {
cout<<"Constructing derived \n";
}
~derived() {
cout<<"Destructing derived \n";
}
};
int main(void) {
derived d();
return 0;
}
Why in this program its not calling constructor?
Can Anyone explain?
.......
The problem is that you are declaring a function here:
// function d(), returns a derived object.
derived d();
What you need is
derived d; // C++03, C++11
or
derived d{}; // C++11 only
This is an "interesting" aspect of C++, where anything that can be parsed as a function declaration will be (provided it is in a context where a function can be declared).
See more on variable initialization in GoTW #1 Variable initialization - or is it?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With