Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Abstract class can't have a method with a parameter of that class

Tags:

c++

I created this .h file

#pragma once

namespace Core
{
    class IComparableObject
    {
    public:
            virtual int CompareTo(IComparableObject obj)=0;
    };
}

But compiler doesn't like IComparableObject obj param if the method is virtual pure, while

virtual int CompareTo(IComparableObject obj) {}

It's ok, however I want it as virtual pure. How can I manage to do it? Is it possible?

like image 673
Francesco Belladonna Avatar asked Nov 26 '10 01:11

Francesco Belladonna


People also ask

Can an abstract method have a parameter?

Yes, we can provide parameters to abstract method but it is must to provide same type of parameters to the implemented methods we wrote in the derived classes.

Can an abstract class be used as a parameter type for methods?

When a class is declared as an abstract class, then it is not possible to create an instance for that class. It can, however, be used as a parameter in a method. An abstract class can't be a static class.

What is not allowed in abstract class?

An abstract class can not be instantiated, which means you are not allowed to create an object of it.

Can an abstract class be a parameter?

Even though A is abstract, you can receive parameters of type A (which, in this case, would be objects of type B ). You cannot really pass an object of class A , though, since A is abstract and cannot be instantiated.


1 Answers

You are trying to pass obj by value. You cannot pass an abstract class instance by value, because no abstract class can ever be instantiated (directly). To do what you want, you have to pass obj by reference, for example like so:

virtual int CompareTo(IComparableObject const &obj)=0;

It works when you give an implementation for CompareTo because then the class is not abstract any longer. But be aware that slicing occurs! You don't want to pass obj by value.

like image 98
3 revs Avatar answered Sep 24 '22 12:09

3 revs