S
subramanian100in
Suppose I have three files namely: 1.h, 1.cpp, 2.cpp
The following is 1.h
----------------------------
#ifndef _1_H
#define _1_H
class Test
{
public:
static std::string str;
void print(const std::string & x = str) { std::cout << x <<
std::endl; }
};
#endif
The following is 1.cpp
--------------------------------
#include <iostream>
#include <string>
#include "1.h"
using namespace std;
extern void fn();
int main()
{
cout << Test::str << endl;
Test obj;
obj.print();
fn();
obj.print();
return 0;
}
The following is 2.cpp
-------------------------------
#include <iostream>
#include <string>
#include "1.h"
using namespace std;
string Test::str = "static const string";
void fn()
{
Test::str = "static const reassigned";
return;
}
When I compile this program with
g++ -std=c++98 -pedantic -Wall -Wextra 1.cpp 2.cpp
it compiles fine. When it is run, the following output is produced.
static const string
static const string
static const reassigned
In 1.cpp, obj.print( ) is called. It is an inline function with
default argument. This default argument is the static data member
whose value is defined in 2.cpp
How does the compiler know the value of the default argument when it
compiles 1.cpp in order to do the inlining. But it prints the value
correctly. I do not understand.
Kindly explain
Thanks
V.Subramanian
The following is 1.h
----------------------------
#ifndef _1_H
#define _1_H
class Test
{
public:
static std::string str;
void print(const std::string & x = str) { std::cout << x <<
std::endl; }
};
#endif
The following is 1.cpp
--------------------------------
#include <iostream>
#include <string>
#include "1.h"
using namespace std;
extern void fn();
int main()
{
cout << Test::str << endl;
Test obj;
obj.print();
fn();
obj.print();
return 0;
}
The following is 2.cpp
-------------------------------
#include <iostream>
#include <string>
#include "1.h"
using namespace std;
string Test::str = "static const string";
void fn()
{
Test::str = "static const reassigned";
return;
}
When I compile this program with
g++ -std=c++98 -pedantic -Wall -Wextra 1.cpp 2.cpp
it compiles fine. When it is run, the following output is produced.
static const string
static const string
static const reassigned
In 1.cpp, obj.print( ) is called. It is an inline function with
default argument. This default argument is the static data member
whose value is defined in 2.cpp
How does the compiler know the value of the default argument when it
compiles 1.cpp in order to do the inlining. But it prints the value
correctly. I do not understand.
Kindly explain
Thanks
V.Subramanian