0

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;
};
  • 1
    Do not put constants in UPPERCASE that's anti-pattern, unless they are preprocessor macro – Slava Mar 04 '16 at 16:01

2 Answers2

0

The problem in your code is that b is getting initialized before NUM_A.

class A {
public:
    const int NUM_A = 1;

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

private:
    const int NUM_A = 1;
    B b;    

    //B b;    
    //const int NUM_A = 1;
};
Jts
  • 3,447
  • 1
  • 11
  • 14
0

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;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Alright, thank you. But I'm curious: if I leave b before NUM_A, why wouldn't it still work if I initialized NUM_A in the constructor right before b? And just to get it straight, the compiler knows that NUM_A exists when it instantiates b, -it simply initializes it later, right? –  Mar 05 '16 at 08:10
  • 1
    The order of initializing in the constructor is ignored. All objects are initialized in the order in which they are declared in the class definition. – R Sahu Mar 05 '16 at 08:15