Public inheritance in C++ is a type of inheritance where the public members of the base class are accessible in the derived class. In other words, when a class is derived from a base class using public inheritance, the public members of the base class become public members of the derived class.
The purpose of public inheritance is to enable the derived class to access the functionality of the base class while also allowing it to extend or specialize the behavior of the base class. For example, a class representing a specific type of vehicle can inherit from a more general class representing a vehicle, allowing the specific class to inherit the general properties of all vehicles while also adding additional specific properties and behavior unique to that specific type of vehicle.
Public inheritance is a powerful mechanism for code reuse and abstraction, allowing programmers to build complex and flexible software systems from simpler building blocks.
#include <iostream>
using namespace std;
class Prim{
protected:
string name;
public:
void setName(string x) {
name = x;
}
};
class Sec : public Prim{
public:
void printName() {
cout << "Name from Prim Cls: " << name << endl;
}
};
int main() {
Sec Object;
Object.setName("Samantha");
Object.printName();
return 0;
}
This is an example of inheritance with a base class called Prim
and a derived class called Sec
. The Sec
class inherits publicly from the Prim
class using the colon :
notation.
The Prim
class has a protected member variable called name
and a public member function called setName()
that takes a string argument x
and sets the value of name
to x
.
The Sec
class has a public member function called printName()
that prints out the value of name
from the Prim
class using the cout
statement.
In the main()
function, an object of the Sec
class called Object
is created, and the setName()
function is called on it to set the value of name
to "Samantha". Then the printName()
function is called on the Object
to print out the value of name
which was set by the setName()
function. The output of the program will be: "Name from Prim Cls: Samantha"
No comments:
Post a Comment