dag roger stokland rui
dag roger stokland rui

Reputation: 173

C++ overriding function

I have tried to solve this problem for several days now without any luck.

Im trying to override a function. This is the header for the parent class:

class DComponent{
public:
virtual void mouseDown(int button, int x,int y){}
};

Header for the child class:

class DButton:public DComponent{
public:
void mouseDown(int button,int x, int y);
};

And the cpp for the child:

#include "DButton.h"
void DComponent::mouseDown(int button, int x,int y){
}

And i get this error:

    1>c:\users\daffern\documents\visual studio 2012\projects\spel\spel\dbutton.cpp(26): error C2084: function 'void DComponent::mouseDown(int,int,int)' already has a body
1>          c:\users\daffern\documents\visual studio 2012\projects\spel\spel\dcomponent.h(13) : see previous definition of 'mouseDown'

I have also tried to not define the virtual function, but then i get link errors.

Any help is greatly appreciated!

Upvotes: 0

Views: 200

Answers (2)

Nicola Pezzotti
Nicola Pezzotti

Reputation: 2357

#include <iostream>

class DComponent{
public:
virtual void mouseDown(int button, int x,int y){
    std::cout << "Parent\n";
}
};


class DButton:public DComponent{
public:
void mouseDown(int button,int x, int y){
    std::cout << "Child\n";
}
};

int main(){
    DComponent parent;
    DButton child;

    parent.mouseDown(0,0,0);
    child.mouseDown(0,0,0);
    return 0;
}

Will print

Parent Child

If you don't want to specify a function for the parent class remember to make it pure virtual

virtual void mouseDown(int button, int x,int y) = 0;

If you want to override also DButton method make it virtual.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

In the header file you define the method, then you re-define it in the source file.

You should define it for the DButton class instead:

void DButton::mouseDown(int button, int x,int y){
}

Also, I recommend you make the DComponent method a pure virtual method, by using

virtual void mouseDown(int button, int x,int y) = 0;

Upvotes: 3

Related Questions