0

I am looking again at inheritance and virtualisation, and by mistake I used parenthesis to create my derived grandchild object in main, 'ryan.'

It ran fine the second time when I took away the () argument brackets, but when I used () it skipped the constructor for grandchild, and also all of the other constructors and destructors.

Can somebody explain what is happening here under the hood, I figured that would still work the same.

#include <iostream>

class Base {
public:
    int age=5;

    Base() {std::cout << "Base Created" << std::endl;}
    virtual ~Base() { std::cout << "Base Deleted" << std::endl; }


};

class son : public virtual Base {
public:
  //  int age = 1;
  son(std::string name) { std::cout <<"son created" << std::endl; }
  son() { std::cout << "son created - default constructor" << std::endl; }
  ~son() { std::cout << "son deleted" << std::endl; }

};



class sonwife : public virtual  Base {
public:
   // int age = 2;
    sonwife() { std::cout << "son wife created - default constructor" << std::endl; }

    sonwife(std::string name) { std::cout << "son wife created" << std::endl; }

    ~sonwife() { std::cout << "sons wife deleted" << std::endl; }

};

class grandchild : public  sonwife, public  son
{
public:
    grandchild() { std::cout << "Grand child created" << std::endl; 
    std::cout << age;
    }

    ~grandchild() { std::cout << "grand child gone!" << std::endl; }
};


int main()
{
    Base *b = new son("Ryan");
    delete b;
    grandchild ryan; // vs. grandchild ryan();
    return 0;
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185

1 Answers1

3

grandchild ryan(); declares a function called ryan which takes no arguments and returns a grandchild. It does not declare a variable called ryan.

Obviously, when ryan is a function, there is no constructor call.

john
  • 85,011
  • 4
  • 57
  • 81