All in all, a constructor is just a special method (member function) that is called when you create an object of that class. Constructors can take arguments, but it isn't necessary. The default constructor will take no parameters.
get...
and
set...
are getter/setter methods. If your variables are private, the only way to see the values/change them from outside the class is to use methods. Think of them like the middle man. You tell them to change something, and they change it for you. You ask them what something looks like and they'll look at it and tell you what it looks like. You just can't change it/look at it directly yourself.
You can use
get...
to get the value of a variable. You can set
set...
to change the value of that variable (but you'll pass a string/int/whatever as a parameter). You can really name those methods anything you want, but prefixing get/set is the usual way of indicating that they are getter/setter methods.
1 2 3 4 5 6 7 8 9 10 11 12
|
class myClass
{
public:
myClass();
~myClass();
void setName(std::string newName);
std::string getName();
private:
std::string name;
};
|
1 2 3 4 5 6 7 8 9
|
void myClass::setName(std::string newName)
{
name = newName;
}
std::string myClass::getName()
{
return name;
}
|
And then somewhere else
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
myClass myClassInstance; //When you create an object, the constructor is called
//std::cout << myClassInstance.name //Can't do this, since 'name' is private.
std::cout << myClassInstance.getName() << std::endl; //Now we can see what the value of 'name' is
//myClassInstance.name = "New Name"; //We can't do this, since 'name' is private. We don't have access here
myClassInstance.setName("New Name"); //We CAN do this. Pass a string to the setter method, and it will change the value of 'name' for us.
std::cout << myClassInstance.getName() << std::endl;
}
|
You associate the string with a variable so that you have something to store it in and refer to it.
If you don't store it in a variable, you can't really do much with it.
Is the header file in the same folder as the file you're trying to include it in? If not, you'll need to provide the path to that file as well.
As an comment on code given above:
1 2 3
|
double getLength( void );
Line(); // This is the a default constructor
Line(x){length = x;};
|
could use some changes;
double getLength( void );
void
does not need to be in there. It can just be
double getLength();
.
void
can be there, but it generally considered a c-style idiom.
Line(x){ length = x;};
Should be
Line(double x){ length = x;}
The type of the parameter must be given.
ebucna wrote: |
---|
to access variable in this case you would say obj2.length |
You wouldn't be able to access it in that way because
length
was declared as
private
.