L
L
lightalex2018-12-24 00:58:25
C++ / C#
lightalex, 2018-12-24 00:58:25

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;
}

I need it to 2 fdisplay , but now it displays 1 i.
I'm trying to achieve this without overriding the function. get
Is it possible to do this? If so, how?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2018-12-24
@lightalex

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;
}

PS
I just tweaked the author's code a bit...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question