C ++: newbie initialization issue

Newbie here. I am looking at a company code.

It looks like there is no member element in class A, but in constructor A it initializes object B, although class A does not contain any member variable of type B (or any member variable at all!).

I think I don’t understand this enough to even ask a question ... so what happens here !? My intuition is that you need a variable before trying to initialize it. How is this possible (or what does it do well) to initialize an object without an object?

.h:

class A: public B
{
public:
     A(bool r = true);
     virtual ~A;

private:
}

.cpp

A::A(bool r) : B(r ? B::someEnumeration : B::anotherEnumeration)
{
}

A::~A()
{
}

Please, help.

Thanks JBU

+3
source share
5 answers

A () B:

class A: public B

- .

+9

ctor ++, noch , super().

0
class A : public B
{
};

class B
{
  public:
  int x;
};

A - B. A B.

, ...

A a;
a.x = 3;

B A.

0

construtor , passying .

You should also know that in the case of a polymorphic class , vptr initialization for the corresponding virtual table is performed only in the constructor.

0
source
class A: public B
{
public:
     A(bool r = true); // defaults parameter 1 as "true" if no arguments provided ex A *pA = new A();
     virtual ~A;

private:
}

.cpp

A::A(bool r) : B(r ? B::someEnumeration : B::anotherEnumeration)
{
  // calls parent class, and initialize argument 1 with some enumeration based on whether r is true or false
}

A::~A()
{
}
0
source

Source: https://habr.com/ru/post/1724677/


All Articles