Question about class and inheritance

Hi,

I'm looking for a way to use inheritance to avoid writing the same function twice.

I have two classes (ClassA and ClassB) which are the same, except for the type in their vector declarations. In ClassA, vec is of type int, while in ClassB, vec is of type string. outData is the function that I want to avoid writing twice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ClassA {
    private:
        std::vector< int > vec;
    
    public:
        void outData( int i );
}

void ClassA::outData( int i ) {
    std::cout << vec.at( i ) << std::endl;

}

class ClassB {
    private:
        std::vector< std::string > vec;

    public:
        void outData( int i );
}

void ClassB::outData( int i ) {
    std::cout << vec.at( i ) << std::endl;
}


Is it possible to create a base class where the the vector type T is specified in ClassA and ClassB?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Base {
    private:
        std::vector< T > vec; //Can the type be specified in inherited classes?

    public:
        void outData( int i );
}

void Base::outData( int i ) {
    std::cout << vec.at( i ) << std::endl;
}

class ClassA: public Base {
   //Can I set T to int?
}

class ClassB: public Base {
   //Can I set T to std::string?
}
Thank you!
Topic archived. No new replies allowed.