My friend and I are very confused about how class arguments work.
nobleman: The working class are uneducated sheep who need to be ruled with a firm hand.
serf: The rich are greedy pigs who exploit the workers.
Whoops, C++ classes...
It seems like the class should kind of set up its own versions of the variables already declared? I'm not sure how the input works.
You certainly do seem confused since it is even hard to decipher what in the heck you are talking about, so here goes. On a very basic level, you can think of a class as merely an array that can hold different types. Think back to arrays. With arrays, you have to declare the type of the array, and the array can only hold values of that type, e.g.
Code:
int numbers[3] = {10, 20, 30};
All the numbers you store in that array have to be int's. On the other hand, a class can store values of any type. You can declare a class like this:
Code:
class Data
{
public:
int age;
double height;
string name;
};
A constructor is used to create an object or "instance" of the class. You give the constructor some values and it stuffs them inside the member variables of the class: age, height, and name. You can define a constructor like this:
Code:
class Data
{
public:
int age;
double height;
string name;
Data(int a, double h, string n)
{
age = a;
height = h;
name = n;
}
};
A constructor has the same name as the class, and you do not specify a return value like you are required to do for other functions.
Something that's very alarming about that constuctor function is that it uses the variable names age, height, and name without first declaring them. Normally, any variables used in a function must be declared as parameters or declared in the body of the function--or else you will get a compiler error. However, when a function is inside of a class, and you want to use the class member variable names inside your function, you do not declare them; you just use their names.
Here is how you would create an object of the Data class:
Code:
#include <iostream>
#include <string>
using namespace std;
class Data
{
public:
int age;
double height;
string name;
Data(int a, double h, string n)
{
age = a;
height = h;
name = n;
}
};
int main()
{
Data myData(18, 6.2, "John");
cout<<myData.name<<endl;
return 0;
}