user2532387 user2532387 - 1 month ago 7
C++ Question

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

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

#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;


But now i need to program the same paradigm with get and set member functions of the class. I need to program somewhat like

#include<iostream.h>

class project
{

std::string name;
int duration;

void setName ( int name1 ); // member functions set
void setDuration( string duration1);

};

void project::setName( int name1)

{

name = name1;

}


void project::setDuration( string 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.
Thanks much

Answer

You have written some set functions. You now need some get functions.

int project::getName()
{
    return name;
}

std::string project::getDuration( )
{
    return duration;
}

Since the data is now private you cannot access it from outside the class. But you can use your get functions in your main function.

std::cout << " the name of the thesis is" << thesis.getName() << '\n';
std::cout << " the duration of the thesis is" << thesis.getDuration() << '\n';
Comments