Question

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.

Was it helpful?

Solution

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/

OTHER TIPS

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

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;   
}

c++ Virtual Function is similar to implements in java

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top