declare in base and define in derived class

Is it possible to declare a method in base class and define in derived class? I'm struggling..
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
  //base.h
class Base{
protected:
    int value;
public:
    void setValue(int);
    int getValue();
};

//derived.h
#include <string>
#include "base.h"

class Derived: public Base{
public:
    std::string name;
};

//derived.cpp
#include "derived.h"
void Derived::setValue(int v){
    value = v;
}

int Derived::getValue(){
    return value;
}

//main.cpp
#include <iostream>
#include "derived.h"

int main(){
    Derived d1;
    d1.setValue(1);
    std::cout << d1.getValue << std::endl;
}
Last edited on
only had a quick glance sorry, but i think you're missing the 'virtual' keyword.

http://en.wikipedia.org/wiki/Virtual_inheritance
Declare it as pure in the (abstract) base class.
Override and define it in (concrete) derived classes.
http://en.wikipedia.org/wiki/Virtual_function#Abstract_classes_and_pure_virtual_functions

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
#include <iostream>

struct base
{
    virtual ~base() {} ;

    virtual void foo() const = 0 ; // pure
};

struct derived : base
{
    virtual void foo() const override { std::cout << "derived::foo\n" ; }
};

struct also_derived : base
{
    virtual void foo() const override { std::cout << "also_derived::foo\n" ; }
};

struct more_derived : derived
{
    virtual void foo() const override { std::cout << "more_derived::foo\n" ; }
};

int main()
{
    const derived a, b ;
    const also_derived c, d ;
    const more_derived e, f ;

    const base* objects[] { &a, &c, &e, &f, &b, &d } ;
    for( auto ptr : objects ) ptr->foo() ;
}

http://coliru.stacked-crooked.com/a/7465f1ab795e14d6
thx for replies guys
Topic archived. No new replies allowed.