Search code examples
c++classinitializationclass-constantsmember-initialization

Member integer changes when directly instantiated from another class


Say I have two classes, A and B. A has an integer, which it displays in the console from its constructor. It also has a member object of B. B displays an integer just like A, but it gets its integer from A when A creates it. The integer must go directly to B's constructor, since it's a const value.

So, when A passes its own integer on to B, I would expect both A and B to display the same number in the console (1). Instead, when B's constructor prints out its integer, it displays -858993460. Why is that? When A instantiates a B object, passing an integer along for B's const int, why does the integer change value?

main.cpp

#include "A.h"

int main() {
A a;
std::cin.get();
return 0;
}

A.h

#pragma once
#include <iostream>
#include "B.h"

class A {
public:
A() :
    b(NUM_A) 
{ std::cout << "A's number: " << NUM_A << std::endl; }

private:
B b;
const int NUM_A = 1;
};

B.h

#pragma once
#include <iostream>

class B {
public:
B (int num) : 
    NUM_B(num) 
{ std::cout << "B's int: " << NUM_B << std::endl; }

const int NUM_B;
};

Solution

  • In the definition of A, member b comes before member NUM_A. As a result, b gets initialized before NUM_A. The value you pass to B's constructor is an uninitialized value.

    Change the order of the members in A. Instead of

    B b;
    const int NUM_A = 1;
    

    use

    const int NUM_A = 1;
    B b;