0

I have this code:

#include <iostream>

class A
{
public:
    A() { std::cout << 'a'; }
    ~A() { std::cout << 'A'; }
};

class B
{
public:
    B() { std::cout << 'b'; }
    ~B() { std::cout << 'B'; }

    A a;
};

int main() {B b; }

Why is it creating object A a; is done before executing B b; arguments?

Is there a priority sequence?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • The instruction `B b;` creates an object of type B, by calling the parameterless constructor `B()`. This constructor has two potential parts, but you only use one: the constructor initialization list and the constructor body. In the constructor initialization list you can tell the compiler how you want your member variables, such as `a`, to be initialized. Since you say nothing, it's default initialized. The constructor body could do lots of things, but once you enter it, your object already exists. It has been initialized. – Daniel Daranas Jun 21 '22 at 15:09
  • Yes there's priority sequence. Since A is a part of B, you have to make an A when you make a B. Since A is only one part of B, it makes sense that A must be made first. – john Jun 21 '22 at 15:14
  • Why: specified behavior. Member variables are constructed and initialized before the body of a constructor is called (so you can use members in the body of the constructor). Destructor bodies are called before members are destructed (so you can use members in the body of your destructor). – Pepijn Kramer Jun 21 '22 at 16:17
  • 1
    This doesn't address the question, but I like that `a` `A` convention for constructors and destructors. Simpler than `constructing A` and `destroying A` and just as clear. – Pete Becker Jun 21 '22 at 16:35
  • @PeteBecker Intuitively, I would have use it in reverse: A a, but that's just me. – Daniel Daranas Jun 21 '22 at 18:14
  • 1
    @DanielDaranas -- the destructor should write the name upside down and backwards. – Pete Becker Jun 21 '22 at 18:40
  • @PeteBecker Maybe we can do that in C++26... – Daniel Daranas Jun 21 '22 at 19:32
  • 1
    Oh wow I didn't notice the comments :D thank you all for the rich informations – mahmod AL-Athamnneh Jun 22 '22 at 17:00

1 Answers1

0

Class members are initializing before executing the constructor of B. Same as:

B() : a() { std::cout << "B"; }
Dark_Phoenix
  • 368
  • 3
  • 14