-3

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;
}
helencrump
  • 1,351
  • 1
  • 18
  • 27
Sandra K
  • 1,209
  • 1
  • 10
  • 21

2 Answers2

4

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>.

Community
  • 1
  • 1
Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104
2

These declarations

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

declare functions c1, c2, c3, c4 and c5 with return type theC and with no parameters.

Write instead

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

Also you should at least include headers <string> and <cstdio> because the program uses declarations from these headers.

Take into account that data member data is declared as private. So you may not access it directly outside the class definition like

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";
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335