How to initialize elements of a base class subobject to 0?

class A
{
  public: int a,b,c;
};

class B: public A
{
   public: int d;
   B():d(0){} // Some hackery needed here
};

int main()
{
   B obj;
   std::cout<< obj.a << std::endl; // garbage
   std::cout<< obj.b << std::endl; // garbage
   std::cout<< obj.c << std::endl; // garbage
   std::cout<< obj.d << std::endl; // 0
}

How could one initialize the data elements a, b, and c of the subobject to 0? I am not allowed to change class A.

+3
source share
5 answers

Try

B() : A() , d(0){}

The value A () initializes A, and since A is a POD, the members will be initialized by default (zero)


+8
source

I tested this as I thought it might work (even without Prasun's answer)

B::B() : A(), d(0)
{
}

may work because you then โ€œinitializeโ€ A.

By the way, this did not happen. Conclusion: 1.32.123595988

This will work:

// put this in B.cpp anonymous namespace
const A a_init = { 0, 0 ,0 };

and then:

B::B() : A( a_init), d(0)
{
}

I am testing with g ++ 4.3.2. THIS now works :

B::B() : A(A()), d(0)
{
}
+4
source

, - , ?

class B: public A
{
    public: int d;
    B():d(0){a=b=c=0;}
}
+1

,

class B: public A
{
   public: int d;
   B():a(0),b(0),c(0),d(0)
   {

   }

};
+1

The correct way, of course, is for constructor A to initialize it. Otherwise, since members are not private, you can assign their values โ€‹โ€‹from within constructor B.

a = 0;

etc. actually works.

+1
source

All Articles