CocaCola
CocaCola

Reputation: 773

Calling a function which belongs to another class

I'm just wondering if there is a way to call a function from another class which is not a derived class.

For example...

If I have class Square which has a function colour, if I have another class Triangle, totally unrealated to Square, can I somehow call the colour funciton of Square on a Triangle object?

I'm wondering if friend can be used here, but from what I have read, it can't, unless I've misunderstood what I've read.

What is the best way to implement this without creating an inheritance relationship?

Upvotes: 0

Views: 112

Answers (3)

daniel gratzer
daniel gratzer

Reputation: 53901

If what your seeking to do is something like this:

Square s;
Triangle t;
t.colour(); // invoke Square::colour() on a Triangle

I'm sorry but you can't, unless you declare a function in Triangle which simply mimics what Square::colour does.

A wise option if you really need that function to be shared is to declare it as a standalone templated function like this:

template<typename Shape>
void colour(Shape s){
  //Do stuff
}

then in order to allow this access to the inner guts of Triangle and Square, make void colour<Triangle>() and void colour<Square>() friends of the appropriate classes.

Upvotes: 1

Syntactic Fructose
Syntactic Fructose

Reputation: 20124

No, sorry to bum you out. But i would recommend using a base class 'shape', and derive shapes from this class.

class Abc //Abstract base class
{
    public:
        virtual ~Abc();                             //destructor
        virtual double Color();           
        virtual double Area() const = 0;                  //pure virtual, MUST be overridden
    private:
        //specific variables that apply to all shapes
};

class Square : public Abc //derived class from pure virtual class
{
    public:
        Square();
        virtual double Color();
        virtual double Area() const; //redefine color here
        ~Square(){}
    private:
        //square vars here
};

Upvotes: 0

bobestm
bobestm

Reputation: 1334

The answer is no, your request is not possible. The colour method is encapsulated within square and will not apply to an unrelated object of a difference class. Either inherit (from shape - I know you said no inheritance), or re-implement the colour method for square as well.

Upvotes: 0

Related Questions