dimanche 7 mars 2021

Why might the compiler try to instantiate a function parameter as though it were a declared variable?

I have a class that takes one parameter to its constructor and has no other constructor:

class MyClass{
        public:
                MyClass(someObject obj);
};

Another class takes this class in as one of its inputs to its constructor:

class OtherClass{
        public:
                OtherClass(MyClass myClassInstance);
};

In my program I use these two classes together:

int main(){

someObject a;
MyClass myClassInstance = MyClass(a);
OtherClass otherClassInstance = OtherClass(myClassInstance);

}

However, when the definition of the OtherClass constructor compiles, it tries calling the constructor to MyClass which causes an error since the MyClass constructor is given 0 parameters (since I didn't really mean to call it at all).

I understand that when a value is declared in c++, it must be instantiated immediately and so for a class value, the constructor is called which could cause an error if the constructor needs input parameters.

However this is not a declared variable, it is an input parameter in a function definition and so I am completely lost as to how the compiler could be mistaking my function parameter definition for a variable declaration and attempting to instantiate the parameter.

Note that these classes and the main are all in separate files but compiled together. I feel pretty confident that I included the headers correctly and am running the compiler correctly but its possible that I made a mistake there. Thanks a lot in advance!

Aucun commentaire:

Enregistrer un commentaire