i am currently learning programming in university and i was messing around and wrote this code and i got curious
class Student{
public:
string name;
string address;
};
class Instructor:public Student {
public:
string name;
string address;
};
int main() {
Instructor Z;
Z.name = "Zombie";
cout << Z.name;
return 0;
}
Shouldn’t C++ return an error since both classes one of which inherits contain the same data type (string) with the same name (name) ? and also when we delegate Z.name = "Zombie";
does the object take from the Student
class or the Instructor
class?
Zoran I is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
You’ll have to qualify which name you actually want to use. The unqualified name is the one from the actual type. Observe:
#include <iostream>
#include <string>
class Student{
public:
std::string name{"empty"};
std::string address{"empty"};
};
class Instructor:public Student {
public:
std::string name{"empty"};
std::string address{"empty"};
};
int main() {
Instructor Z;
std::cout << Z.name << "n";
std::cout << Z.Student::name << "nn";
Z.name = "Zombie";
std::cout << Z.name << "n";
std::cout << Z.Student::name << "nn";
Student& S=Z;
std::cout << S.name << "n";
S.name="Student";
std::cout << S.name << "nn";
std::cout << Z.name << "n";
std::cout << Z.Student::name << "nn";
}
stieber@gatekeeper:~ $ g++ Test.cpp && ./a.out
empty
empty
Zombie
empty
empty
Student
Zombie
Student
So, there are simply two distinct name
variables. Same for address, of course.