C++ Abstract Class: constructor yes or no?

后端 未结 8 1872
轮回少年
轮回少年 2020-12-04 08:45

A class with one (or more) virtual pure functions is abstract, and it can\'t be used to create a new object, so it doesn\'t have a constructor.

I\'m reading a book t

8条回答
  •  执笔经年
    2020-12-04 08:59

    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 
    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题