Mateon1
Mateon1

Reputation: 368

Pass an instance of a class deriving from a base class into a function

I have a class hierarchy in my C++ program:

class DEBase {
public:
    virtual double distance(vec3) = 0;
};

class Sphere : public DEBase {
private: ...
public:
    Sphere(...) {...}
    ...
    double distance(vec3 p) {...}
};

class XZPlane : public DEBase { 
... 
public: 
    XZPlane(...) {...} 
    ... 
    double distance(vec3 p) {...} 
} 
...

I want to pass any object deriving from DEBase into a function.

void addObject(DEBase o) {
    someVector.push_back(o);
}

However, that does not work. I get an error message saying error: cannot declare parameter 'o' to be of abstract type 'DEBase'

When I Googled a bit, I found that you can pass in objects by reference.

void addObject(DEBase &o) {
    someVector.push_back(&o);
}

The function now compiles properly, however invoking it seems impossible. I tried addObject(new Sphere(...)), I tried addObject(&new Sphere(...)), however, nothing works.

How can I make it work?

Upvotes: 0

Views: 518

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

(I already answered this in chat, two hours ago. Here's what I said.)

It completely depends. This is not a question about polymorphism; it is a question about object ownership and about how you intend to construct your objects.

Right now your biggest problem is that you're trying to pass a pointer (or, in your nonsensical latter example, a pointer to a pointer!) when the function does not expect one. Remember, references are not pointers.

It does kind of seem like accepting pointers into that function would make a bit more sense. Consider making it some kind of C++11 smart pointer.

But, again, this has absolutely nothing to do with inheritance or polymorphism (besides the fact that using it prevents you from taking the new objects by value).

Upvotes: 2

basav
basav

Reputation: 1495

x *ptr=new x; candidateFunction(*ptr);

new returns a pointer, not a reference to a value

Upvotes: 0

Phil Lello
Phil Lello

Reputation: 8639

You are mixing references and pointers; What are the differences between a pointer variable and a reference variable in C++? covers the differences.

If you want to stick with references, you could use:

Sphere globe(...);

addObject(globe);

If you are creating Sphere's on the fly, using new, you could use:

Sphere *globe = new Sphere(...);

addObject(*globe);

Upvotes: 1

Related Questions