Answer the question
In order to leave comments, you need to log in
How to correctly override functions and types when inheriting a class?
Good day!
I'm trying to redefine the function and type of the variable when inheriting a class.
Actually code:
#include <stdio.h>
#include <iostream>
#include <typeinfo>
class A {
public:
A(){};
~A(){};
typedef int custom;
custom num = 1;
int get() {
return 1;
}
void print() {
std::cout << get() << " " << typeid(num).name() << "\n";
}
};
class B : public A {
public:
B() : A(){};
~B(){};
typedef float custom;
int get() {
return 2;
}
};
int main() {
B b;
b.print();
return 0;
}
2 f
display , but now it displays 1 i
. get
Answer the question
In order to leave comments, you need to log in
Yes, it can be done, but you need to use templates. Something like:
#include <stdio.h>
#include <iostream>
#include <typeinfo>
template <class T>
class A {
public:
A(){};
~A(){};
typedef T custom;
custom num = 1;
T get() {
return num;
}
void print() {
std::cout << get() << " " << typeid(num).name() << "\n";
}
};
class B : public A<float> {
public:
B() : A() { num = 2.f; };
~B(){};
};
int main() {
B b;
b.print();
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question