-1

In c++ is there a reson why you would pass a reference to a base class to a constructor of a derived class? Why would you want to do this?

Here is a basic example:

#include<iostream>
using namespace std;

class Base
{
   int x;
public:
    virtual void fun() = 0;
    int getX() { return x; }
};

// This class ingerits from Base and implements fun()
class Derived: public Base
{
    int y;
public:
    Derived(Base& object);
    void fun() { cout << "fun() called"; }
};
pelican brady
  • 185
  • 2
  • 9
  • 5
    Did you find code like this somewhere and wondering why they did that? If you did that code might have some context for why they did that. Otherwise we could only guess why they provided that constructor. – NathanOliver Aug 22 '18 at 16:30
  • 2
    Obviously the `object` instance passed in is a _different_ instance than what is currently being constructed, so presumably the constructor here calls methods on the instance passed in to get information used in the construction of the current instance. – 500 - Internal Server Error Aug 22 '18 at 16:34
  • 3
    Do you want us to just make up a list of reasons why a person might hypothetically want to do this? It will be long and many of them will be specific. – David Schwartz Aug 22 '18 at 16:42

3 Answers3

1

Typically, arguments are passed to constructors because the state of the arguments can be used to initialize the state of the object that is being constructed. Same applies to this case.

Non-const reference arguments can be (and nearly always are) used to modify the referred object.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

In c++ is there a reason why you would pass a reference to a base class to a constructor of a derived class?

There is usually one reason why reference to an object would be passed to a constructor, does not really matter if that object type related to consttructed one or not - to construct this type you need information from that object. Using lvalue reference instead of const one could mean either bad design or ctor would need to modify passed object or keep non-const reference/pointer to it.

Slava
  • 43,454
  • 1
  • 47
  • 90
0

I would think the question is "why pass the base class reference instead of the derived class reference?". If so, the reason Base& is passed instead of Derived& is that the former allows you to pass an OtherDerived& reference, given that OtherDerived inherits Base. This is called polymorphism and is quite a thing in C++.

Here's pretty much the same question, but with a function instead of a constructor.

ARentalTV
  • 344
  • 1
  • 12