0

In the following program:

#include <iostream>

using namespace std;

class first{

    public:
        first(){cout << "FIRST" << endl;}

};


class second: public first{

    public:
        second(){cout << "SECOND" << endl;}

};


int main(){

    second obj();

    return 0;
}

Nothing is outputed.When instantiating an object of second , both constructors are called, so why is there no output?

Turns out, that if in the main function the command is: second* pointer = new second(); the output is:

First
Second

Why does that happen?

zach
  • 95
  • 1
  • 7
  • 1
    `second obj();` is interpreted as declaration of function with name `obj` that returns object of type `second` and takes no arguments. To create an object use uniform initialization `second obj{};` or simply `second obj;` or `second obj = second();` – Yksisarvinen Jun 03 '20 at 08:32
  • 1
    try `first f();` to realize that inheritance isnt the problem – 463035818_is_not_an_ai Jun 03 '20 at 08:35
  • Use [ES.23: Prefer the {}-initializer syntax](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es23-prefer-the--initializer-syntax) to avoid this problem. – Thomas Sablik Jun 03 '20 at 08:38

0 Answers0