The major and essential features that make a program object-oriented are:
- Encapsulation: The ability to hide the implementation details of a class from outside users and provide a well-defined interface for interaction with the class.
- Inheritance: The ability to create new classes that are derived from existing classes and inherit their properties and behavior.
- Polymorphism: The ability to define different behaviors for the same function or method depending on the context in which it is called.
- Abstraction: The ability to define and use abstract data types that can be manipulated without knowing their underlying implementation details.
Now, if a base and derived class each include a member function with the same name, the member function of the derived class will be called by an object of a derived class. this is because the derived class overrides the member function of the base class with its own implementation.
Here's an example to illustrate this:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() {
cout << "Drawing a rectangle" << endl;
}
};
int main() {
Shape* s = new Rectangle();
s->draw();
delete s;
return 0;
}
In this example, we define a base class "Shape" with a virtual member function 'draw()', which prints a message indicating that a shape is being drawn. We then define a derived class 'Rectangle' that overrides the 'draw()' function to print a message indicating that a rectangle is being drawn.
In the 'main()' function, we create a pointer 's' of the 'Shape*' and assign it to a new "Rectangle" object. We then call the 'draw()' function on the pointer 's'. Since 's' is a pointer to a 'Shape' object, but it points to a 'Rectangle' object, the 'draw()' function of the 'Rectangle' class is called. This is because the 'Rectangle' class overrides the 'draw()' function of the 'Shape' class with its own implementation,
No comments:
Post a Comment
If you have any doubts, please let me know