Interface in C++

Associate
Joined
16 Nov 2011
Posts
1,000
Location
127.0.0.1
I am wanting to implement an interface in C++ like you do in Java.

In java it's very easy, all you need to do is create an interface and then create a variable of that interface, then instantiate it with an implementation of the interface.

But how would you do that in C++.

For example, if you have the class base with the virtual method void print(); in the header file. Then you have a class derived with inherits from base and where you then implement void print();. If you then create a main class where you do something like -

main.h
base something;

main.cpp
something = derived();
something.print();

How would you do that?
 
Associate
Joined
9 Jun 2004
Posts
423
Code:
#include <string>
#include <iostream>
#include <memory>

class IDuck
{
public:
    virtual std::string quack() = 0; //pure virtual
    virtual ~IDuck() {}
};

class LolDuck : public IDuck
{
public:
    virtual std::string quack()  
    {
        return "lol";
    }
};

class RoflDuck: public IDuck
{
public:
    virtual std::string quack()  
    {
        return "rofl";
    }
};

int main()
{
    std::unique_ptr<IDuck> duck(new LolDuck());
    std::cout << duck->quack() << std::endl;

    duck.reset(new RoflDuck());
    std::cout << duck->quack() << std::endl;
    return 0;
}
 
Associate
OP
Joined
16 Nov 2011
Posts
1,000
Location
127.0.0.1
Code:
#include <string>
#include <iostream>
#include <memory>

class IDuck
{
public:
    virtual std::string quack() = 0; //pure virtual
    virtual ~IDuck() {}
};

class LolDuck : public IDuck
{
public:
    virtual std::string quack()  
    {
        return "lol";
    }
};

class RoflDuck: public IDuck
{
public:
    virtual std::string quack()  
    {
        return "rofl";
    }
};

int main()
{
    std::unique_ptr<IDuck> duck(new LolDuck());
    std::cout << duck->quack() << std::endl;

    duck.reset(new RoflDuck());
    std::cout << duck->quack() << std::endl;
    return 0;
}

Thanks for your help.
 
Back
Top Bottom