Question on constructors in Inheritance

  • Thread starter yungman
  • Start date
  • #36
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
 
  • #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

Suggested for: Question on constructors in Inheritance

Replies
89
Views
3K
3
Replies
73
Views
3K
Replies
4
Views
826
Replies
3
Views
497
Replies
63
Views
2K
Replies
13
Views
337
Replies
13
Views
629
Replies
89
Views
3K
Replies
23
Views
1K
Back
Top