Reputation: 187
#include<iostream>
using namespace std;
class A
{
protected:
int m_nValue;
public:
A(int nValue):m_nValue(nValue)
{
cout << m_nValue << endl;
}
};
class B: public A
{
public:
B(int nValue): A(m_nValue)
{
cout << m_nValue << endl;
}
int getValue()
{
return m_nValue;
}
};
int main()
{
B b(4);
cout << b.getValue() << endl;
return 0;
}
Here, in the above program I am not declaring m_nValue
again in the Derived class. In the output, I see only junk values getting displayed rather than displaying value "4".
Please explain this.
Upvotes: 1
Views: 98
Reputation: 172924
You're trying to initialize m_nValue
with m_nValue
itself. The parameter nValue
(passed in the value 4
) is not used at all. That's why m_nValue
has only garbage value.
You might want
B(int nValue): A(nValue)
{
cout << m_nValue << endl;
}
Upvotes: 3
Reputation: 133577
Your constructor is bugged B(int nValue): A(m_nValue)
. You are not using nValue
to pass it to A
constructor but the instance variable which is uninitialized.
Upvotes: 2
Reputation: 1629
B(int nValue): A(nValue)
You should initialize A
with nValue
rather than m_nValue
Upvotes: 2