Velpus Captiosus
Well-Known Coder
Isnt abstraction the opposite process of inheritance in C++?When we create a abstract class , we create the basis for other classes while inherited classes take some basis and add details.
By registering with us, you'll be able to discuss, share and private message with other members of our community.
SignUp Now!class Shape {
public:
virtual double getArea() = 0; // Pure virtual function, must be implemented by derived classes
virtual void printInfo() {
std::cout << "This is a shape." << std::endl;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() override {
return 3.14159265 * radius * radius;
}
void printInfo() override {
std::cout << "This is a circle with radius " << radius << "." << std::endl;
}
};
I guess the difference isnt between Abstraction and Inheritance but between Abstraction and Inheritance+Polymorphism.Thanks a lot btw!Well, in a very simple and short line, when you want to define a common interface and hide implementation details, you should use abstraction, and when you want to promote code usability, classes, and other implementations, you should use inheritance.
Example of Abstraction
Code:class Shape { public: virtual double getArea() = 0; // Pure virtual function, must be implemented by derived classes virtual void printInfo() { std::cout << "This is a shape." << std::endl; } };
Example of inheritance
Code:class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double getArea() override { return 3.14159265 * radius * radius; } void printInfo() override { std::cout << "This is a circle with radius " << radius << "." << std::endl; } };
I hope you are clear now.
Thanks
Isnt abstraction the opposite process of inheritance in C++?When we create a abstract class , we create the basis for other classes while inherited classes take some basis and add details.
Thanks a lot!Have a good day!No, abstraction and inheritance are not opposite processes in C++. Abstraction involves simplifying complex reality by creating abstract classes that provide a common interface or blueprint for other classes. Inheritance, on the other hand, allows classes to inherit properties and behaviors from other classes, including abstract classes, to build on that foundation and add specific details. Abstraction sets the foundation, and inheritance builds upon it, so they are complementary concepts.
Code Forum is a community platform where coding enthusiasts can connect with other developers, engage in discussions, ask for help, and share their knowledge with a supportive community. It's a perfect place to improve your coding skills and to find a community of like-minded individuals who share your passion for coding.
We use essential cookies to make this site work, and optional cookies to enhance your experience.