Classes, constructors.. lost

Hey!

I would like to know what uses this programme can have, because i'm kinda lost with Bucky's now.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;


class name{
    public:
        void setname (string x){
            name = x;
        }
        string getname1(){
            return name;
        }

      
    private:
        string name;
        
};


int main()
{

    name nameobject;
    nameobject.setname("Little Stuart");

    cout << nameobject.getname();
    return 0;
}
Last edited on
It's not very useful program other than demonstrating how classes and member functions work.
Demonstrates getter and setters methods common to many classes. You typed the second method wrong though it should be:
1
2
3
string getname(){
    return name;
}
Last edited on
yes, but what uses can have a program with constructors?
This doesn't demonstrate constructors. But constructors allow you to set the class or structs internal variables when it is declared.
If I recall correctly, Bucky is actually introducing you a little bit to data hiding through the use of a really simple "getter" method in a simple class. There really isn't much else substantive about this class.

Classes hide certain data by making some members private or protected. Private members cannot be accessed by outside classes or functions. Protected members work the same way, but allow derived classes to manipulate protected members.

One way to work around this is to employ public member functions called getter methods that can be used by non-member functions/objects to access information stored by private data. That's what Bucky is doing in this example: simply showing you how to use a public getter method.

As to your second question, Constructors are really important member functions. They construct the object and in the process are useful for initializing members. The example above does not explicitly declare a constructor so a default constructor is created. Like other functions, you can overload them. Constructors also can perform other operations such as copying one object to another and type casting. They can also be used, with an appropriate destructor, to handle dynamic memory allocation operations within the class.



Topic archived. No new replies allowed.