Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
Let me first explain the code and then I will ask a question.

The main looks as follows:

#include <iostream>
#include "A.h"
#include "B.h"

int _tmain(int argc, _TCHAR* argv[])
{
   B b;

   std::cout << &constA << std::endl;
   b.Print();

   return 0;
}
//-----------------------------

and A.h:

class A
{
public:
   A( int v): val(v) {}
 
private:
   int val;
};

const A constA(10);

//----------------------------

and B.h + B.cpp

file B.h :

class B
{
public:
  void Print();

};

file B.cpp:

#include "B.h"
#include "A.h"
#include <iostream>

void B::Print()
{
   std::cout << &constA << std::endl;
}

//----------------------------


OK. In header file A.h is declared global read-only object constA. It shall be only one such object in application.
But when I prints its address in main two times (one explicitly in cout line and then calling Print method of B class) I got two different addresses. Why does it occur? How to achieve one address of this const in the whole code?
Posted
Updated 15-Jan-10 4:21am
v3

You have defined the variable in the header file, then included the file into two separate compilation units. This means that the compiled files B.obj and main.obj will both contain variables called constA.

To make it a global constant, it needs to be declared in the header file, but defined once only:

In A.h:
extern const A constA;


In A.cpp:
#include "A.h"

const A constA(10);
 
Share this answer
 
Is there a reason you need to do this? I just read here[^] that a compiler is free to store a const anywhere, thus it could actually be stored in multiple places. My guess is that a copy of constA is being stored on the local call stack in each instance.

BTW- It seems like what you really want is a Singleton object. There are many articles on how to make one of those.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900