0

Silly question here, but I can't seem to find a clear answer because of my lack of experience with terminology. Say I have a class

Class Char
{
    friend void function(Char object);
    protected:
        float x, y;
};
void function(Char object){
    // access object.x and object.y
}

And that class has several child classes:

Class Char1 : public Char
{
   ...
};

Class Char2 : public Char
{
   ...
};

Is it possible to use a Char1 or Char2 object as a parameter for function(Char object), since they both inherit the values that the function will use?

Thanks and sorry for the silly question

seMikel
  • 246
  • 2
  • 14

3 Answers3

1

Yes. But you should really pass by pointer or reference.

So you should define Char like this:

class Char{
    public:
        friend void function(Char &c); // or const Char &     

    protected:
        float x, y;
};

and function like this:

void function(Char &c){}

(which you probably wanted to do anyway)

so that you aren't copying 2 floats every time you call the function

and you can pass in Char or any derived class of Char

RamblingMad
  • 5,332
  • 2
  • 24
  • 48
1

Your function is being passed an argument by value, so Char1 will be partially copied (sliced) to the stack as Char. If you want to deal with the original Char1 object, declare passing by reference:

void function(Char &c) {
    // ...
}
Community
  • 1
  • 1
bereal
  • 32,519
  • 6
  • 58
  • 104
0

I agree with @lubo-antonov that this code does not have correct syntax, however if I understand correctly that "Char1" and "Char2" are meant to be classes that inherit from a class called "Char" then yes, you can create a function for example function foo(Char obj) that will receive an object of type "Char1" or "Char2" as a parameter.

in need of help
  • 1,606
  • 14
  • 27