I would like to know if it is possible, like in java or c#, to define a subclass with a specific template type (overriding the superclass generic type).
In my code I wanna do the following thing :
class AbstractClass<T>
class ASubClass : AbstractClass<int>
Here is my code (trying to learn c++ inheritance, I know code is wierd):
///// SUPER CLASS ////
AbstractClass.h
#ifndef ABSTRACTCLASS_H
#define ABSTRACTCLASS_H
#include <string>
template <typename T>
class AbstractClass
{
protected:
int m_X, m_Y;
T m_T;
public:
AbstractClass(int x, int y, const T& t);
virtual std::string getName() = 0; // virtual + = 0 means its abstract
virtual int getX();
int getY();
T getT();
};
#endif // ABSTRACTCLASS_H
AbstractClass.cpp
#include "AbstractClass.h"
template <typename T>
AbstractClass<T>::AbstractClass(int x, int y, const T& t) : m_X(x), m_Y(y), m_T(t) {
}
template <typename T> // have to define T everytime because even if its not called, it might be
int AbstractClass<T>::getX() {
return m_X;
}
template <typename T>
int AbstractClass<T>::getY() {
return m_Y;
}
template <typename T>
T AbstractClass<T>::getT() {
return m_T;
}
//// SUB CLASS ////
ASubClass.h
#ifndef ASUBCLASS_H
#define ASUBCLASS_H
#include <AbstractClass.h>
#include <string>
class ASubClass : AbstractClass<int>
{
private:
char* m_firstname;
char* m_lastname;
public:
ASubClass(int x, int y, const int& t, char* firstname, char* lastname);
std::string getName() override; // would also be abstract if this was not implemented
int getX() override;
};
#endif // ASUBCLASS_H
ASubClass.cpp
#include "ASubClass.h"
#include <string>
ASubClass::ASubClass(int x, int y, const int& t, char* firstname, char* lastname)
: AbstractClass<int>(x, y, t), m_firstname(firstname), m_lastname(lastname) {
}
std::string ASubClass::getName() {
return std::string(m_firstname) + " " + m_lastname;
}
int ASubClass::getX() {
return AbstractClass::getX() + m_Y;
}
I am getting the following errors :
D:\...\ASubClass.cpp|4|undefined reference to `AbstractClass<int>::AbstractClass(int, int, int const&)'|
and
D:\...\ASubClass.cpp|13|undefined reference to `AbstractClass<int>::getX()'|
Is it possible in c++ to make java and c# generic type equivalences that work during build time and where we don't need to do checks during runtime ?