Interfaces


Hi,

I am developing interfaces to a module. the problem i am facing is as mentioned below:
the class hierarchy is something like this:

class Iface
{
public:
virtual void create()=0;
virtual void getsomething()=0;
};

class base: public Iface
{
public:
virtual void getsomething();
};

class derived: public base
{
public:
void getsomethingelse();
}

class derived2: public derived
{
public:
void create();
}


now in our code we are creating objects of derived classes like below:

main()
{
Iface * obj = new derived2;
/* some code */
Iface *obj = new derived;
/* some code */
}

it is giving linking errors because when we override derived class object, it does not find the implementation of create() method in derived.

does any one have any idea about how to resolve this? i don't want to have dummy methods that were declared in the Interface class in all the class hierarchy.

Please let me know if you have any solutions for this.

Thanks in Advance...

Why are create() and getsomething() part of the same interface?
Did you actually implement both of the pure virtual functions in the derived classes?
Galik wrote:
Did you actually implement both of the pure virtual functions in the derived classes?


He did not. Hence my question. If it is meaningful to have a derived class that does not implement one of the methods, then both methods do not belong in the same interface.

Interface Segregation Principle: clients should not be forced to depend on interfaces they do not use.

http://www.oodesign.com/interface-segregation-principle.html

Hi PanGalactic,

Thank you for the link provided.

We have a requirement that the interface class is the only way to create the derived classes.

could you please elaborate? what i understand is we should have separate interface classes for derived and derived2 classes?

Thanks much


Yes, that is what the Interface Segregation Principle states.

Consider doing something like this:

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
class Creatable
{
public:
    virtual void create()=0;
};

class Gettable
{
public:
    virtual void getsomething()=0;
};

class base: public Gettable
{
public:
    virtual void getsomething();
};

class derived: public base
{
public:
    void getsomethingelse();
}

class derived2: public derived, public Createable
{
public:
    virtual void create();
}


And then in your code...
1
2
3
4
5
6
7
8
9
main()
{
    Gettable* obj1 = new derived2;
    /* some code */
    Gettable* obj2 = new derived;
    /* some code */
    
    Creatable* obj1_alias = dynamic_cast<Creatable*>(obj1);
}


Does that help?
Topic archived. No new replies allowed.