Nope Nope - 4 months ago 8
C++ Question

I have data but it says can not resolve variable "data"

We are learning classes and I am doing my assignment to write a class and 5 different objects and to display the difference.

The professor said that we should use default constructors and the book says this:


A default constructor is a constructor which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter).


I am doing exactly what the teacher did; can you please tell me why it says it can't find
data
?

#include <iostream>

using namespace std;

class theC
{
private:
string data;
public:
theC() {
printf("default\n");
}
};

int main()
{
theC c1();
theC c2();
theC c3();
theC c4();
theC c5();

c1.data = "different object 1";
c2.data = "different object 2";
c3.data = "different object 3";
c4.data = "different object 4";
c5.data = "different object 5";
cout << c1.data << c2.data << c3.data << c4.data << c5.data;
return 0;
}

Answer

Your code has several issues:

Issue one: Is in these lines:

theC c1();  
theC c2();      
theC c3();  
theC c4();  
theC c5();

Here you are trying to declare an instance(object) of your class theC. However, your compiler considers it as a Function Declaration and the Prototype of a function called c1 that takes zero or no parameters(() is empty) and returns an object of type theC.

The correct syntax for declaring an object of your class would : theC c1;

So your Default Constructor will be called as soon as you declare a variable of your class. It is how it works.

Issue two: Also, you can not access any "Private" member. You would need it to be "Public" or you would need to use getters and setters.

Issue three: You are using a the string class without #include <string>.