I'm having a hard time trying to figure out how to access and change base class data member using derived class method. Following code is a sample of what I want to do.
class A
{
protected:
string name;
public:
A():name("Name 1"){}
void DisplayA()
{
cout<<name<<endl;
}
};
class B : public A
{
public:
void Change()
{
cout<<"Enter New Name: ";
getline(cin,name);
}
void DisplayB()
{
cout<<name<<endl;
}
};
main()
{
A Obj1;
B Obj2;
Obj1.DisplayA();
Obj2.Change(); // I want this method to change the name in Base class too.
Obj2.DisplayB();
Obj1.DisplayA(); // This method should now display the new name that we set in Change();
}
You must define name as static std::string
because modifying non-static members of an object change them only for that object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.