简体   繁体   中英

derived class constructor call base constructor

I have a base class Array and a derived class NumericArray

class Array{//Array.h
private: int size;

public: Array();//Default constructor
        Array(int index);// Initialize with size
        GetSize();//getter function
};

class NumericArray:public Array
{//NumericArray.h

public: NumericArray();//Default constructor
        NumericArray(int index);// Initialize with size
};

I know how to call the default Array constructor in NumericArray class. But when it comes to the NumericArray(int index), I have no idea. Since the derived class cannot access the size in base class, I think I should use getter function in base class. But how should I do?

Thanks.

What you can do is call the constructor of the base class whenever the derived class has an object instantiated. You can do this relatively easily by using something similar to member-init:

class Base
{
private:
    int size;
public:
    Base(int param) { size = param;}
    //rest of the code here
};

class Derived : public Base
{
private:
   //other data members
public:
    Derived(int param): Derived(param) { //set rest of data}
};

This passes param to the constructor of Base , and lets it do whatever with it. Derived doesn't need direct access to size in Base because it can use what is already in place to handle it. Here is a pretty good explanation if you want a more in depth explanation and examples. (scroll about 2/3 of the way to get to constructors)

Since size is a private variable in the base class Array , it cannot be accessed in the child class NumericArray .

There are two ways to access size in the child class NumericArray :

  1. Make size a protected variable in the base class Array and access it in the child class NumericArray .

     protected: int size; 
  2. Write a getter public function ( GetSize() ) in the base class Array that returns size , and the child class NumericArray can just call this getter public function in the constructor of the child class using super.GetSize() per this link .

     public: GetSize() { return size } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM