0

So I've been trying to make a test program that shows the difference between passing an object by reference, and by value.

I'd like the constructor of ClassB to take in two arguments: a reference to ClassA, and the value of ClassA.

I've been able to run the program when the constructor only takes in the reference. However, when I added the second parameter (for value of ClassA), I get the error "no matching function for call to 'ClassA::ClassA()'".

#include <iostream>
using namespace std;

class ClassA{
    int num;

public:
    ClassA(int _num){
        num = _num;
    }

    int getNum(void){
        return num;
    }

    void addToNum(int value){
        num += value;
    }
};

class ClassB {
    ClassA * classPointer;
    ClassA classValue;

public:
    ClassB(ClassA& referencedClass, ClassA value){ // HERE I get the error
        classPointer = &referencedClass;
        classValue = value;
    }

    int getPointedNum(void){
        return classPointer->getNum();
    }

    int getValueNum(void){
        return classValue.getNum();
    }
};

int main(int argc, char *argv[]) {

    ClassA classA (20);
    ClassB classB (classA, classA);
    classA.addToNum(5);
    cout << "classB.getPointedNum(): " << classB.getPointedNum() << endl;
    cout << "classB.getValueNum(): " << classB.getValueNum() << endl;


    return 0;
}

Does anybody have some idea of what's going on here?

Thanks.

MaxwellCE
  • 23
  • 1
  • 3

2 Answers2

0

You need to explicitly initialize classValue by calling its constructor, because you have deleted its default constructor by defining a non-default constructor.

This has to be done in the member initialization list of the constructor, because member variables are initialized before entering the constructor body:

ClassB(ClassA& referencedClass, ClassA value)
: classPointer(&referencedClass), classValue(value) // member initialization list
{
    // constructor body
}

This will initialize classPointer with the value &referencedClass and call the default copy constructor of ClassA with value.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • There is no default constructor at all. Saying a constructor is deleted, is different to saying it doesn't exist. A deleted constructor is considered for overload resolution and if it is selected then the program is ill-formed. – M.M Mar 22 '15 at 05:36
0

The error you are seeing corresponds to a missing initializer for the member classValue.

When you use

ClassB(ClassA& referencedClass, ClassA value) { ... }

the compiler tries to initialize classValue using the default constructor. Since there isn't one, it is not able to initialize classValue.

You can use:

ClassB(ClassA& referencedClass, ClassA value) :
    classPointer(&referencedClass_,
    classValue(value)
{
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270