Wednesday 8 April 2015

Overloaded Member Functions

The members of a derived class can base the same name as those defined in the base class. An object of a derived class refers to its own functions even if the y are defined in both the base class and the derived class. In the derived class there can also be functions with the same name as those in base class. It results in ambiguity. The compiler resolves the conflict by using the following rule :

If the same member exists in both the base class and the derived class, the member in the derived class will be executed.

If we want to invoke the base class member function, then the syntax is

Base_classname::memberfunction();

Sample Program

#include <iostream.h>
class B
{
protected:
int x;
int y;
public:
void read(void)
{
cout<<”X in class B”;
cin>>x;
cout<<”Y in class B”;
cin>>y;
}
void show(void)
{
cout<<”X in class B is “<<x<<endl;
cout<<”Y in class B is “<<y<<endl;
}
};
class D : public B
{
protected:
int y;
int z;
public:
void read(void)
{
B::read();
cout<<”Y in class D”;
cin>>y;
cout<<”Z in class D”;
cin>>z;
}
void show(void)
{
B::show();
cout<<”Y in class D is “<<y<<endl;
cout<<”Z in class D is “<<z<<endl;
}
};
void main()
{
D obj;
Cout<<”enter the data for object of class D”;
Obj.read();
Cout<<”Content of object of class D”<<endl;
Obj.show();
// or we can use Obj.B::show()
}

No comments:

Post a Comment