c++ - derived class has same member variable name as base class -
#include<iostream> using namespace std; class { protected: int m_nvalue; public: a(int nvalue):m_nvalue(nvalue) { cout << m_nvalue << endl; } }; class b: public { 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 above program not declaring m_nvalue
again in derived class. in output, see junk values getting displayed rather displaying value "4". please explain this.
you're trying initialize m_nvalue
m_nvalue
itself. parameter nvalue
(passed in value 4
) not used @ all. that's why m_nvalue
has garbage value.
you might want
b(int nvalue): a(nvalue) { cout << m_nvalue << endl; }