+ 1
Why we make abstracts class in c++???
3 Answers
+ 7
I think in this way..
āAn abstract class can't be instantiated.(object of abstract class can't be created)
āAbstract classes are used so that they can be used as base class for deriving new classes.
An example ,
You have to create two classes.
1. Worker
2. Manager
The common attributes in both can be 'age', 'experience', 'name' , 'skills'. Basically these can be implemented in class 'Employee'.
This class can also have some common methods like getName , setName.
But wait! If you instantiate an Employee , either Manager or a Worker just using this Employee class will you be able to calculate salary for them properly?
I mean Manager will obviously get paid more than a normal Worker even if they work for same 'time'
So methods like getSalary that aren't common to classes to be derived shouldn't be implemented in base class! We better implement them in derived class.
Summary: keep common attributes in Abstract class and use it to derive base classes that will implement functions uncommon to both =)
+ 6
Hussain Sahir
Continued..
Above inheritance can be implemented without making 'Employee' abstract but we make it abstract because we can't instantiate just an Employee without knowing what kind of Employee it is....
Making Employee abstract will insure you'll not instantiate an incomplete employee (who can't getSalary(); )
moreover data members to be derived should be protected or public
Here the function getSalary() will be virtual like...
virtual float getSalary()=0;
//making Employee abstract.
This pure virtual function now can actually *must be implemented in derived classes.
Making it virtual also means that you'll have access to it when pointing by a base class pointer.
+ 4
May I know why someone just downvoted my first answer ?
I'll be glad if you tell the reason to hate my answer. I'll appreciate to hear what's wrong in it , correct me if wrong . That's it.
Downvoting without letting me know my fault don't make any sense :'(