3

I am programming a polymorphic program in C++ that requires the use of Derived/Inherited classes. My base class is called ClassA and my Derived class is called ClassB. I have a separate class called varClass that is the datatype for a parameter in the constructor of my Base class, ClassA. I get this error message in the following constructor in ClassA.cpp:

Field 'object_var' must be initialized

#include "ClassA.h"
#include "varClass.h"

ClassA::ClassA(const classVar &O, const int &p) {}

Why must objects from a separate concrete class be initialized before allowing them to be used a parameters of functions in separate classes? I have tried putting a forward declaration of the classVar class in ClassA with no luck. How can I fix this to allow an argument of a datatype from a separate class? If I give it an initialization, how can I ensure each value passed to this constructor is unique and not just overridden by the initialization value?

Here is the rest of the relevant code. I am not going to show the Derived classes as I do not believe they are part of the problem, but decided to mention them since I am a novice programmer and that could possibly be the issue.

// ClassA.h

#ifndef CLASSA_H
#define CLASSA_H

#include "varClass.h"

class ClassA {

protected:
    const classVar &object_var; // The problem lies here
    unsigned var1;

 // ... more code follows

public:
    ClassA(const object &O, const int &p);

// ... more code follows

};

#endif 

Header and implementation of objectVar class are irrelevant to issue. That class is a standard concrete class.

jshapy8
  • 1,983
  • 7
  • 30
  • 60

2 Answers2

2

You should initialize reference in the constructor's initializer list:

ClassA(const classVar &O, const int &p)
 : object_var(O) {    
}

P.S. Make sure constructor's signatures in header and source files match.

Community
  • 1
  • 1
Ivan Aksamentov - Drop
  • 12,860
  • 3
  • 34
  • 61
0

object_var needs to be initialized in the constructor because it is a reference. There is no other way to have it refer to something.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56