user2738698
user2738698

Reputation: 578

Java "implements" equivalent in c++?

I want to make a priority queue class that I can reuse again and again in different programs, which stores only one type/class in it.

I can keep out any other types/classes from entering the queue by using compareTo methods, but that means the queue class should require the compareTo method in all of types/classes that enter the queue.

I know that in Java, you can make a class implement Comparable to ensure that that class implements a compareTo method. So I was wondering if there was something similar in c++.

As well, I can't use templates, so, any alternatives would be appreciated. The reason that templates are off limits aren't known to me either, the one asking for this program won't shed some light on that. It must be purely my own code for the priority queue as well.

Upvotes: 1

Views: 4307

Answers (4)

Aman Aggarwal
Aman Aggarwal

Reputation: 4005

Since, you are reluctant to use templates.

You might also consider typeid in c++. e.g. and more info here.

Also consider a related stackoverflow question.

A working example which might suit you follows: You can see the output here

#include <typeinfo>
#include <iostream>
#include <string>

using namespace std;

class QueueAbleObject{
};

class A : public QueueAbleObject{

};
class B:  public QueueAbleObject{

};




class Queueu{
      string mQueueDataType ;
public:

    void SetType(const  std::type_info& typeInfo){
        mQueueDataType  = typeInfo.name();  
        cout << "list type " <<      mQueueDataType << endl ;
    }

    bool Insert( QueueAbleObject*  obj , const std::type_info& objTypeInfo )    
    {
        if( objTypeInfo.name() != mQueueDataType ){
            cout << " Incompatible Object type  " <<objTypeInfo.name() << endl;
            return false;
        }

        //do insertionn

        return true;

    }
};


int main(){
    Queueu q;
    q.SetType( typeid(A) );

    A a;
    bool res = q.Insert(&a , typeid(a));
    cout << " Insertion of  A :  " <<  res << endl;

    B b;
    res = q.Insert(&b , typeid(b));
    cout << " Insertion of B : " <<  res << endl ;


    return 0;   
}

Upvotes: 1

Ajinkya
Ajinkya

Reputation: 1

c++ Virtual Function is similar to implements in java

Upvotes: 0

bakercp
bakercp

Reputation: 924

It sounds like you want to build interfaces in C++. You should check out pure virtual base classes. An example can be found here:

How do you declare an interface in C++?

More can be found here.

http://www.learncpp.com/cpp-tutorial/126-pure-virtual-functions-abstract-base-classes-and-interface-classes/

Upvotes: 7

Saksham
Saksham

Reputation: 9380

You may create a pure virtual function in the base class and inherit it. In that case, the derived class has to implement the function, otherwise it itself becomes an abstract class

Upvotes: 3

Related Questions