Question on constructors in Inheritance

  • Thread starter yungman
  • Start date
In summary, the object of the derived class MoreTrouble has its own member variable message, which is different from the member variable message of the base class Trouble.
  • #36
jbunniii said:
Your attempt to call cout is not inside any function definition. This is not allowed. Did you mean to do it inside the Dclass constructor? If so, you have to define a Dclass constructor!
Sorry I did not see your post till now.

Thanks
 
Technology news on Phys.org
  • #37
Here's the same code you posted, minus the comments. It's still tight
C++:
#include<iostream>
using std::cout;
class Bclass
   {public: int a = 2, b = 3;
    void fun0() { cout << " Bclass fun0()." << "\n\n";}
    void fun1() { cout << " Bclass fun1()." << "\n\n";}};
class Dclass : public Bclass
{public: int a = 5;
    cout << " Dclass.a = " << a << ", Bclass.a = " << Bclass.a << "\n\n";
    void fun1() { Bclass::fun1(); }
    void fun2() { cout << " Dclass fun2()." << "\n\n";} };
int main()
   {Dclass DC2; DC2.fun0(); DC2.fun1(); DC2.fun2();
    cout << " DC2.a= " << DC2.a << ", DC2.b= " << DC2.b << "\n\n";
}
When you wrote "It's one line of code per line." you probably meant one instruction per line, but in main() you have a declaration and three function calls all on one line.

Here's the same code as above, but spaced out to increase readability.
C++:
#include<iostream>
using std::cout;

class Bclass
{
public:
    int a = 2, b = 3;
    void fun0() { cout << " Bclass fun0()." << "\n\n";}
    void fun1() { cout << " Bclass fun1()." << "\n\n";}
};

class Dclass : public Bclass
{
public:
    int a = 5;
    cout << " Dclass.a = " << a << ", Bclass.a = " << Bclass.a << "\n\n";
    void fun1() { Bclass::fun1(); }
    void fun2() { cout << " Dclass fun2()." << "\n\n";}
};

int main()
{
    Dclass DC2;
    DC2.fun0();
    DC2.fun1();
    DC2.fun2();
    cout << " DC2.a= " << DC2.a << ", DC2.b= " << DC2.b << "\n\n";
}
With a reasonable amount of whitespace, it's much more obvious that in the declaration section of Dclass, you have an executable statement (cout << ...) mixed in with the declarations.
 
Last edited:
  • Like
Likes jbunniii and Vanadium 50

Similar threads

Replies
36
Views
2K
Replies
89
Views
5K
Replies
17
Views
2K
Replies
36
Views
4K
Replies
2
Views
984
Replies
7
Views
2K
Replies
25
Views
2K
Replies
35
Views
3K
Replies
6
Views
1K
Replies
36
Views
2K
Back
Top