Douglas Edward
Douglas Edward

Reputation: 155

Class inheritance and redefining type of members c++

Say we have a class called Base. In this class there is a vector and functions that operate on this vector. I want to create derived classes that are different based on the type of vector (one inherited class for int, another for char...etc). Some methods are exactly the same for the different derived classes, (either int, char, bool...), others are completely different. The methods need access to the vector elements.

Consider the following code:

class Base {
public:
    std::vector<int> vec;

    virtual void Print() { std::cout << vec[0]; }

};

class Derived : public Base {
public:
    std::vector<bool> vec;
};

int main() {
    Base * test = new Derived;
    test->vec.push_back(5);
    test->Print();
    system("PAUSE");
}

This prints an int and not a boolean.

Upvotes: 0

Views: 831

Answers (1)

maditya
maditya

Reputation: 8886

You cannot change the type of the vector in the base class simply by deriving it. A derived class has all the members of the base class, AS WELL AS its own members.

In your code, the derived class as a vector<int> AND a vector<bool>. The Print function that gets called is the base class's Print function, since the derived class doesn't implement its own. The base class's Print function prints the vector<int>.

You need to use templating instead of inheritance. You can do something like:

template <class T>
class Generic {
public:
    std::vector<T> vec;

    void Print() { std::cout << vec[0]; }

};

int main() {
    Generic<bool> * test = new Generic<bool>;
    test->vec.push_back(5);
    test->Print();
    system("PAUSE");
}

In the above code, Generic is a class that holds a vector of T's (where T could be int, bool, whatever). You instantiate a class of a particular type by specifying the type, e.g. Generic<bool>. Generic<bool> is different from Generic<int>, which is different from Generic<double>, etc. in the same way that vector<int> is different from vector<bool>, etc.

Upvotes: 2

Related Questions