set and get the value of different class members in a class

hi all, i am new to c++ programming and i have written a simple class program to display the name and duration of the project

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
class project
{

public: 
std::string name;
int duration; 
};

int main ()
{
project thesis;  // object creation of type class
thesis.name = "smart camera"; //object accessing the data members of its class
thesis.duration= 6;

std::cout << " the name of the thesis is" << thesis.name << ;
std::cout << " the duration of thesis in months is" << thesis.duration;
return 0;



now i am trying to the write the same program with the usage of member functions using set and get member functions. i have tried the following


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
34
35
36
37
38
39
#include<iostream.h>

class project
{

std::string name;
int duration; 

// Member functions declaration
void setName ( int name1 ); 
void setDuration( string duration1); 

};
// Member functions definitions
void project::setName( string name1)
{
name = name1;
}
void project::setDuration( int duration1);
{
duration=duration1;
}

// main function

int main()
{
project thesis;  // object creation of type class

thesis.setName ( "smart camera" );
theis.setDuration(6.0);

//print the name and duration

return 0;

}

}


I am not sure whether above code logic is correct, can someone please help me how to proceed with it.
Last edited on
You should change the parameters from the member functions: setName should take a string and setDuraction an int. In your code it's the other way around.
I changed it, i want to know whether this logic is correct ? and how would i print the name and duration in the main function.

can you please help
Yeah, the logic is OK. You would implement get member functions like this:
1
2
3
4
5
6
7
8
9
std::string project::getName() const
{
    return ( name );
}

int project::getDuration() const
{
    return ( duration );
}


Then in main() you can use them like this:
1
2
3
4
5
6
7
project thesis;  // object creation of type class

thesis.setName ( "smart camera" );
theis.setDuration(6.0);

//print the name and duration
std::cout << thesis.getName() << ' ' << thesis.getDuration() << std::endl;


btw: recently on this forum there has been a discussion if getters/setters are good design or not, have a look here: http://www.cplusplus.com/forum/lounge/101305/
Last edited on
Topic archived. No new replies allowed.