problem with virtual methods

Jul 27, 2013 at 8:57pm
Hi I have problem with code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

class Base {

    ...

    public:
        virtual const wchar_t *Me() const{
            return L"Base";
        }

        virtual bool IsMe(const wchar_t *me_char) final{
            if ( wcscmpi( me_char, Me() ) == 0) {
                return true;
            } else {
                return false;
            }
        }

        ...

    };

    class Child : public Base {

    public:

        virtual const wchar_t *Me() {
            return L"Child";
        }

    };

    Child obj;

    obj.Me(); -> show Child;

    obj.IsMe("Child") -> show false because Me in IsMe is Base


How I could get IsMe from Child not from base?
Jul 27, 2013 at 9:03pm
closed account (Dy7SLyTq)
first on line 35 you shouldnt have a ; in the middle, secondly pretty sure final is a java keyword, with const being the c++ equivalent, thirdly if you want it ot return true, you need to rewrite it in child except Me() would return "Child". thats the advantage of virtual functions. if all of your methods dont share a name then they dont need to be virtual
Jul 27, 2013 at 9:16pm
but is any chance to get method without rewrite function?

I must always write IsMe() in any child class when it is always the same code?
Jul 27, 2013 at 9:18pm
@OP: respect the prototype
You are adding a non-const version of Me() in the Child class.

@DTSCode: http://en.cppreference.com/w/cpp/language/final (nothing to do with const)
Jul 27, 2013 at 9:18pm
closed account (Dy7SLyTq)
you dont have to, but if you want your code to return true, yes
Jul 27, 2013 at 9:23pm
@DTSCode: see the template pattern
Jul 27, 2013 at 9:23pm
Oh I got it the problem is use the const keyword, many thanks for you.

I delete final and virtual from me IsMe, and i remove const from Me() and it works.
Jul 27, 2013 at 9:24pm
closed account (Dy7SLyTq)
@ne555: sorry we posted at the same time so i didnt see your link. ill check it out now
Jul 27, 2013 at 9:26pm
closed account (Dy7SLyTq)
is that c++11? never heard of it before (which doesnt say much unfortunately :p). so i thought he was doing something like

const int myfunc() const { ... }
and got javas final mixed up with our const

@op: sorry for misleading you tehn
Jul 27, 2013 at 9:29pm
yes, it is c++11.
Jul 27, 2013 at 9:30pm
closed account (o1vk4iN6)
1
2
3
4
5
if ( wcscmpi( me_char, Me() ) == 0) {
                return true;
            } else {
                return false;
            }


Redundant code...

return wcscmpi(me_char, Me()) == 0;

is equivalent.
Topic archived. No new replies allowed.