Advertisement
//C++ Example of function overriding
#include<iostream>
using namespace std;
class A //superclass
{
public:
void name() //function name() in class A
{
cout<< "A" << "\n";
}
};
class B : public A //subclass of A
{
public:
void name() //function name() of class A is overridden in class B
{
cout<< "B" << "\n";
}
};
int main()
{
A ob;
ob.name();
B ob1;
ob1.name(); //call to overridden function name() in B class
}
A
B
//C++ Argument list of the overriding function must match with the argument list of function being overridden.
#include<iostream>
using namespace std;
class Maths
{
public:
int num1, num2;
int mathOperation(int a, int b) //performing addition operation on two integers.
{
num1=a;
num2=b;
return (num1+num2);
}
};
//Maths class is inherited by Subtract class.
class Subtract : public Maths
{
public:
int mathOperation(int a, int b) //mathOperation is overridden to perform subtract operation on two integers.
{
num1=a;
num2=b;
return (num1-num2);
}
};
int main()
{
Subtract ob ;
cout<< ob.mathOperation(5,2);
}
3
Advertisement
//C++ The return type of the overriding function must be the same or a subtype of return type of the function being overridden.
#include<iostream>
using namespace std;
class A
{
public:
A returnObject() //function returnObject() has return type A
{
A ob;
cout<< "Returning an object of A" << "\n";
return ob;
}
};
class B : public A
{
public:
B returnObject() //overridden function returnObject() has return type B(subtype of A)
{
B ob;
cout<< "Returning an object of B" << "\n";
return ob;
}
};
int main()
{
A ob;
ob.returnObject();
B ob1;
ob1.returnObject();
}
Returning an object of A
Returning an object of B
//C++ The access level of an overriding function cannot be more restrictive than the access level of a function being overridden.
#include<iostream>
using namespace std;
class A
{
public:
void showName() //function showName() has "public" access
{
cout<< "A";
}
};
class B : public A
{
private:
void showName() //overridden function showName has a more restrictive "private" access
{
cout<< "B";
}
};
int main()
{
A a;
a.showName();
B b;
b.showName();
}
A.cpp: In function 'int main()':
A.cpp:32:12: error: 'void B::showName()' is private within this context
b.showName();
^
A.cpp:20:6: note: declared private here
void showName() //overridden function showName has a more restrictive "private
" access
^~~~~~~~
//C++ Instance methods of superclass can only be overridden if they are first inherited by its subclass.
#include<iostream>
using namespace std;
class A //superclass
{
private:
void showMethod() //showMethod() has private access and it cannot be overridden.
{
cout<< "A";
}
};
class B : public A //subclass
{
private:
void showMethod() //creating a new function showMethod() in class B
{
cout<< "B";
}
};
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement