user233320
user233320

Reputation: 385

Passing a reference of a base class to another function

Here is the problem i am facing, does anyone have solution?

Class A: public class B
{
 // I want to pass a reference of B to Function
}

void ClassC::Function(class& B)
{
  //do stuff
}

Upvotes: 0

Views: 729

Answers (2)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422026

The way you are declaring the class is wrong:

class A : public B // no more class keyword here
{

}; // note the semicolon

void ClassC::Function(const B &b) // this is how you declare a parameter of type B&
{
}

You simply need to pass the object of type A to the Function. It'll work. It's good to declare the parameter as const if you want to take derived types too. To pass the this instance, you'd simply call:

classCObject.Function(*this);

Upvotes: 6

Mark Rushakoff
Mark Rushakoff

Reputation: 258258

Are you just having trouble with the syntax? It should be

void ClassC::Function(B& b)
{
    b.DoSomething();
}

to make b a reference of type B.

Upvotes: 1

Related Questions