1

I'm learning C++ and am a fair beginner at it. I'm having a little trouble understanding why there's a logical or a runtime error. Can anyone explain what I did wrong?

I already know a solution by removing my functions in the classes A and B and simply defining it in the constructor but if that's the correct way why can't I initialize it in some other function like I have done?

#include <stdlib.h>
#include<iostream>
using namespace std;

class A
{
  protected:
  int x;
  public:

void Init()
{
  x = 10;
 }
   };

class B
{
protected:
    int x;
public:

     void Init()
    {
        x = 20;
    }
};

class C: public A, public B
{
public:
   void Test()
   {

      cout << "A's x is " << A::x;
      cout << "\nB's x is " << B::x;
   }
};

int main()
{
    C c;
    c.Test();
    return 0;
}

I was Expecting A normal result that i would usually get in java with "this" function.

i.e.

A's x is 10
B's x is 20

But what I'm getting is

A's x is 8
B's x is 50
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • `Init` is not the name of a constructor, it's just a class. Constructor is named the same as the class is named, ie. `class A { A() { ... this will run at constructiong ... } };` – KamilCuk May 05 '19 at 15:31

2 Answers2

0

Neither A::Init() nor B::Init() are being called. A::x and B::x are uninitialized.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

In C++ you should provide your class of a default constructor. A default constructor is also required for classes that you want to store in an STL container like std::vector.

Probably in Java the compiler do it in your behalf and your code works.

Anyway, in the specific case, you should initialize both base classes calling

A::Init();
B::Init();

before call derived c.Test().

class C : public A, public B
{
   public:
   void Test()
    {
       A::Init();
       B::Init();
       cout << "A's x is " << A::x;
       cout << "\nB's x is " << B::x;
    }
};


   //output
   A's x is 10
   B's x is 20

Regards

JPix
  • 16
  • 1
  • 2