If The base abstract class does not have a constructor, how would you assign values to firstname , lastname
members for any derived class, when you are creating an object of the derived class?
Suppose there is a Manager Class
derived from Employee
which adds Salary
data and implements earning()
. Now Employee
is an abstract class but Manager
is a concrete class
and hence you can have an object of Manager
. But when you are instantialting Manager
, you need to initialize/assign values to members inherited from base class i.e. Employee
. One way is that you can have setFirstName() & setLastName()
in the base class for this purpose and you can use them in the constructor for derived class i.e. Manager
or more convenient way would be to have a constructor in your base abstract class Employee
.
See the code below:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Employee {
public:
Employee(const char*, const char*);
~Employee();
const char* getFirstName() const;
const char* getLastName() const;
virtual double earnings() const=0; // pure virtual => abstract class
virtual void print() const;
private:
char* firstname;
char* lastname;
};
Employee::Employee(const char* first, const char* last){
firstname= (char*) malloc((strlen(first)+1)*sizeof(char));
lastname= (char*) malloc((strlen(last)+1)*sizeof(char));
strcpy(firstname,first);
strcpy(lastname,last);
}
Employee::~Employee(){
free(firstname);
free(lastname);
cout << "Employee destructed" << endl;
}
const char* Employee::getFirstName() const{ return firstname;}
const char* Employee::getLastName() const{ return lastname; }
void Employee::print() const{
cout << "Name: " << getFirstName() << " " << getLastName() << endl;
}
class Manager:public Employee{
public:
Manager(char* firstname,char* lastname,double salary):
Employee(firstname,lastname),salary(salary){}
~Manager(){}
double earnings() const {return salary;}
private:
double salary;
};
int main(){
Manager Object("Andrew","Thomas",23000);
Object.print();
cout << " has Salary : " << Object.earnings() << endl;
return 0;
}