Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Constructor not calling [duplicate]

#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?
.......

like image 523
Asap Avatar asked Feb 27 '26 07:02

Asap


1 Answers

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?.

like image 67
juanchopanza Avatar answered Feb 28 '26 21:02

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!