This code demonstrates how to use scope resolution operator to access a method that is overloaded in multiple classes in a hierarchy:
#include <iostream>
using namespace std;
class Prim{
public:
void sameName() {
cout << "I am from Prim Cls" << endl;
}
};
class Sec : public Prim{
public:
void sameName() {
cout << "I am from Sec Cls" << endl;
}
};
class Third : public Sec{
public:
void sameName() {
cout << "I am from Third Cls" << endl;
}
};
int main() {
Sec Object;
Object.Prim :: sameName();
Third Object_T;
Object_T.Sec :: sameName();
return 0;
}
The code defines three classes: Prim
, Sec
, and Third
. Sec
is derived from Prim
, and Third
is derived from Sec
. All three classes have a method named sameName()
, which is overloaded in each derived class.
In the main()
function, two objects are created, one of Sec
and one of Third
. The scope resolution operator ::
is used to access the sameName()
method of the base class Prim
of Sec
object and the sameName()
method of the base class Sec
of Third
object.
When Object.Prim :: sameName()
is called, it calls the sameName()
method of Prim
class because it is explicitly qualified with the name of the class. Similarly, Object_T.Sec :: sameName()
calls the sameName()
method of the Sec
class.
No comments:
Post a Comment