Home > Back-end >  How to access correct class member?
How to access correct class member?

Time:12-05

I've been running across this snippet of code and after execution I found out that everything compiles and executes fine (the int code member of the derived class is set to 65). However I was wondering how would one be able to access the char code member of the derived class?

#include <iostream>
using namespace std;

class base {
public:
    base() : code('B') { }
    char code;
};

class derived : public base
{
public:
    int code;
};

int main(void)
{
    derived d;
    d.code = 65;
    std::cout << d.code;
};

CodePudding user response:

By specifying the correct scope for the base member variable using a qualified name lookup, as follows:

d.base::code = 'x'
std::cout << d.base::code << '\n';

See this section on qualified name lookups for more details.

  • Related