set and get the value of different class members in a class - c++

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

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

Related

Constructor error anytime I use private variables in VS Code

We're learning about constructors in class and I was trying to experiment with an overloaded constructor. When I run my program I keep getting an error written in the color red that says...
~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
^This only happens when I try to use private variables, when everything is public nothing goes wrong.
///Here's my code
#include <iostream>
using namespace std;
class JCole {
private:
string song;
string album;
int albumNum;
JCole::JCole(string _song, string _album, int _Num) {
song = _song;
album = _album;
albumNum = _Num;
}
};
int main() {
JCole album1("Punchin the clock", "The Off-Season", 6);
JCole album2("ATM","KOD",5);
cout << album1.song << " " << album1.album << " " << album1.albumNum << endl;
cout << album2.song << " " << album2.album << " " << album2.albumNum << endl;
return 0;
}
Your constructor is declared as private because you haven't changed the access setting.
Try this:
class JCole {
private:
string song;
string album;
int albumNum;
// Insert:
public:
JCole::JCole(string _song, string _album, int _Num) {
song = _song;
album = _album;
albumNum = _Num;
}
};
A private constructor is a nasty thing; only members of the class can call it. Thus wreaking havoc with external code that wants to instantiate this class.
Also, you can use many public:, private:, protected: within your class and in any order.

Changing scope from member to global function

I'm attempting to change a print function from a member to a global function without modifying the main function. I am unable to compile this without modifying the main function, though.
class Student
{
char* name;
long ssn;
public:
Student (char*, long);
//void print();
char * getName ( );
long getSsn ( );
};
Student::Student(char* temp_name, long temp_ssn)
{
name = new char[strlen(temp_name) +1];
strcpy(name,temp_name);
ssn = temp_ssn;
}
char * Student::getName()
{
return name;
}
long Student::getSsn()
{
return ssn;
}
void print()
{
cout << "Name: " << getName() << endl;
cout << "SSN: " << getSsn() << endl;
}
int main ( )
{
Student S1("Mike", 222222222L);
S1.print();
return 0;
}
In particular, I was wondering if it is necessary to include void print(); in the public: section of the Student class? Or would that make it a member function?
Is it actually possible to do this without modifying the main function?
How do I access the class from a global function? Am I going to go crazy? Thank you, everyone.
Here's how to make print a global function.
class Student
{
char* name;
long ssn;
public:
Student (char*, long);
char * getName ( );
long getSsn ( );
};
Student::Student(char* temp_name, long temp_ssn)
{
name = new char[strlen(temp_name) +1];
strcpy(name,temp_name);
ssn = temp_ssn;
}
char * Student::getName()
{
return name;
}
long Student::getSsn()
{
return ssn;
}
void print(Student& s)
{
cout << "Name: " << s.getName() << endl;
cout << "SSN: " << s.getSsn() << endl;
}
int main ( )
{
Student S1("Mike", 222222222L);
print(S1);
return 0;
}
Notice that I've added a Student& parameter to print, it has to know which student to print after all. And in main I've changed the way print is called so it has a Student parameter, instead of calling a method on Student.
I'm sure the point of the exercise is to show that you can achieve the same effects using either global functions or member functions.

trying to get different outputs from polymorphic function

Hi StackOverflow community!
I'm expecting different outputs depending on the class of object to be printed but that's not the case.
Medium.h
#include "Datum.h"
#include "Person.h"
class Medium
{
public:
Medium(std::string initTitel);
virtual ~Medium(void);
void ausgabe() const;
bool ausleihen(Person person, Datum ausleihdatum);
void zurueckgeben();
unsigned int getID();
protected:
static unsigned int currentID;
unsigned int ID;
std::string titel;
bool status;
Datum datumAusgeliehen;
Person personAusgeliehen;
};
Medium.cpp
#include "Medium.h"
#include <string>
#include <iostream>
unsigned int Medium::currentID = 1;
Medium::Medium(std::string initTitel): titel(initTitel), status(false)
{
ID = currentID++;
}
Medium::~Medium(void) {}
void Medium::ausgabe() const
{
std::cout << "ID: " << ID << std::endl;
std::cout << "Titel: " << titel << std::endl;
switch (status)
{
case true:
std::cout << "Status : Das Medium ist seit dem "
<< datumAusgeliehen << " an "
<< personAusgeliehen.getName() << " ausgeliehen."
<< std::endl;
break;
case false:
std::cout << "Status: Medium ist zurzeit nicht verliehen." << std::endl;
break;
}
}
The function prints ID, title and status to console.
Now depending on the type of Medium, I would like to print extra information using the function void ausgabe() const.
Example: If the Medium is a book(in german buch = book), information about author should be printed, in addition to other information available in Medium class. i.e, I have got the subclass called Buch which also has an void ausgabe() const function, which should print this extra information in class Buch.
Buch.h
#include "Medium.h"
class Buch: public Medium
{
public:
Buch();
Buch(std::string initTitel, std::string initAutor);
virtual ~Buch();
void ausgabe() const;
private:
std::string autor;
};
Buch.cpp
#include "Buch.h"
Buch::Buch(std::string initTitel, std::string initAutor): Medium(initTitel), autor(initAutor)
{ // TODO Auto-generated constructor stub }
Buch::~Buch() { // TODO Auto-generated destructor stub }
void Buch::ausgabe() const
{
Medium::ausgabe();
std::cout << "Autor: " << autor << std::endl;
}
As far as I have: In the class Buch, while calling the output function ausgabe() the extra information autor will be printed automatically. But for the remaining informations from Medium class, could you help. Thanks for your help :)
Now depending on the type of Medium to be printed, I would like to add
extra information to be printed. E.g. if the Medium is a book,
information about author should be printed too.
So you are looking for dynamic-polymorphism. Then, you need to make void ausgabe()const function to virtual in your base class(Medium), in order to call it polymorphically. And you need to override it in other subclasses(for instance class Buch). In the given code anyways these are not there. In addition to that, you also need virtual destructor at your base class.
Then in your class Buch's ausgabe() should be:
void ausgabe()const override
{
Medium::ausgabe(); // call first base class's ausgabe()
std::cout << "autor :" << autor << std::endl;
}
Then in your main, you can do this: See an example code here
int main ()
{
std::unique_ptr<Medium> some_objects[2];
some_objects[0] = std::make_unique<Medium>("Some Title");
some_objects[1] = std::make_unique<Buch>("Title 2", "user9775960");
for(auto& obj_type: some_objects)
obj_type->ausgabe();
return 0;
}
PS: always try to post English written code in the community, so that everybody can follow.

C++: Derived classes, "no matching constructor" error

I've been working on this assignment for a while. Here's the instructions:
You are to design an abstract class called Employee whose members are
as given below (make them protected):
Data members: char *name, long int ID
Two constructors: A Default constructor // intitialize data memebrs to
the default values and a copy constructor
Methods: setPerson (char *n, long int id) //allows user to set
information for each person A function called Print () // should be a
virtual function, that prints the data attributes of the class. and a
destructor
Also define two classes that derived from class Employee, called
Manager and Secretary. Each class should inherit all members from the
base class and has its own data members and member functions as well.
The Manager should have a data member called degree for his/her
undergraduate degree (e.g. diploma, bachelor, master, doctor), the
Secretary should have her contract (can be a Boolean value 1/0 for
permanent/temporary).
All member functions of derived class should be overrided from their
base class.
Write the following main() to test your classes
int main() {
Employee * p = new Manager(“Bruce Lee”, 0234567, “Dr.”);
P.print();
Secretary p2;
p2.setPerson(“Wilma Jones”, 0341256, “permanent”);
delete p;
p = & p2;
p.Print();
return 0;
}
This is everything I've come up with so far, but I'm pretty sure it's riddled with mistakes and that my arguments and variable types are all off.
#include <iostream>
using namespace std;
class Employee{
protected:
char *name;
long int ID;
public:
Employee();
Employee(Employee&);
void setPerson(char * n, long int eID) {
name = n;
ID = eID; };
virtual void Print(){
cout << "Name: " << name << endl;
cout << "ID: " << ID << endl; };
};
class Manager: public Employee {
protected:
char *degree;
public:
void setPerson(char * n, long int eID, char * d){
name = n;
ID = eID;
degree = d;
};
void Print() {
cout << "Name: " << name << endl;
cout << "ID: " << ID << endl;
cout << "Degree: " << degree << endl;
};
};
class Secretary: public Employee {
protected:
bool contract;
public:
void setPerson(char * n, long int eID, string c){
name = n;
ID = eID;
if (c == "permanent") contract = true;
else contract = false;
};
void Print(){
cout << "Name: " << name << endl;
cout << "ID: " << ID << endl;
cout << "Contract: " << contract << endl;
};
};
int main() {
Employee * P = new Manager("Bruce Lee", 0234567, "Dr.");
P.Print();
Secretary P2;
P2.setPerson("Wilma Jones", 0341256, "permanent");
delete P;
P = & P2;
P.Print();
return 0;
}
I'm getting an error on line 62 (the first line of the main code):
No matching constructor for initialization of Manager
I've tried reading similar questions, but they haven't helped me much. I think the most confusing thing is contract being a bool value and the use of char arguments. Any guidance at all is appreciated.
The error you're getting is pretty straight-forward: you don't have any constructor for Manager (or Employee) that takes a string, integer (?), and string as arguments.
You have declared the constructor employee but not defined it.
Look at the class employee, Under publc you have declared
Employee();
Employee(Employee&);
But you have not defined the function. You need
Employee :: Employee()
{
bla bla bla
}
and another one for the other signature.

Understanding Data Structures and Classes C++

So I'm having trouble understanding how Struct works in C++ I have develop a code in which I've been playing for a while but I don't seem to display for the results I'm looking for. I don't get any compiler errors or mistakes so it seems to be running ,This is what I have ...
Question: How do I display the results in "void Save_Player_Name(Player_Data Player)" later on in the future... ?
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
}Customer[1];
int main()
{
Save_Name_File();
}
void Save_Name_File()// will capture the name of the player
{
int n;
int i = 1;// number of players
//cin.get();
for (n=0; n<i; n++)// will the player
{
cout << string(30, '\n');
cout << "Player Amount " << n << " Out of : " << i;
cout << "\n Please enter the name you wish to play \n\n Name: ";
getline (cin,Customer[n].Player_Name);
}
}
void Save_Player_Name(Player_Data Player)// will store the name of the player in a file
{
ofstream scores_data;
scores_data.open ("scores.dat", std::ios_base::app);
cout << Player.Player_Name << endl;
scores_data<< Player.Player_Name << "\n";
scores_data.close();
}
Edit: minor fixes.
Edit: Added class consideration.
Question: How do I display the results in "void
Save_Player_Name(Player_Data Player)" later on in the future... ?
If you are asking how to read the data in from a file:
const bool readFile()
{
ifstream ip;
ip.open("scores.dat", ifstream::in);
if( !ip )
{
printf("Unable to open file.");
return false;
}
// loop over every line in the file
string bffr;
while( getline(ip, bffr) )
{
<do something>
}
}
If you are referring to how to access the data stored in the variable:
Technically, you should be able to do the following from main:
Save_NameFile();
printf("Player name: %s", Customer[n].Player_name.c_str());
However, having Customer be global is bad for a number of reasons. Instead, you should create a local instance in main and pass it to your functions. You will then be able to access it in the same manner.
Note: I used printf instead of cout. I would recommend getting familiar with it. You'll need to include stdio.h, I believe.
Also, you need to make sure you are passing your struct by reference. There are a number of reasons why you should do this, but you will need to in order to get the data back out.
void Save_Player_Name(Player_Data &Player) {<<stuff here>>}
You should also be declaring your functions before main:
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
};
void askUserForName(Player_Data &);
void writeNameToFile(Player_Data &);
void main()
{
Player_Data player;
askUserForName(player);
return;
}
void askUserForName(Player_Data &player)
{
<<do stuff>>
writeNameToFile(player);
return;
}
etc.
Unless you really need to use a struct, I would recommend going with classes. Structs make everything (variables and methods) public by default, whereas classes are private by default. In reality, structs and classes are identical--you can use them fairly interchangeably (don't shoot me!); in practice, structs are generally used when you need to aggregate some data (i.e., variables) without methods.
Your class might end up something like this (I haven't tested it, and I've been coding in Python lately, so please forgive any minor errors):
class PlayerData
{
public:
PlayerData()
{
}
~PlayerData()
{
}
void askUserForName()
{
<<code here>>
}
void writeNameToFile()
{
<<code here>>
// also write to screen
printf("[Write to console] name: %s\n", this->name_.c_str());
}
private:
std::string name_;
};
void main()
{
PlayerData player;
player.askUserForName();
player.writeNametoFile();
return;
}
In reality, you'd want to use a header file and separate things out, but I'll leave that for another day.
You haven't called the method that saves the player after you call Save_Name_File()
You need some logic fixes for your code
#include <iostream>
#include <fstream>
using namespace std;
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
}Customer[1];
void Save_Player_Name(Player_Data Player)// will store the name of the player in a file
{
ofstream scores_data;
scores_data.open ("scores.dat", std::ios_base::app);
cout << Player.Player_Name << endl;
scores_data<< Player.Player_Name << "\n";
scores_data.close();
}
void Save_Name_File()// will capture the name of the player
{
int n;
int i = 1;// number of players
//cin.get();
for (n=0; n<i; n++)// will the player
{
cout << "Player Amount " << n << " Out of : " << i;
cout << "\n Please enter the name you wish to play \n\n Name: ";
getline (cin,Customer[n].Player_Name);
Save_Player_Name(Customer[n]);
}
}
int main()
{
Save_Name_File();
return 0;
}