• After more than 30 years running websites and forums I am retiring.

    I have made many friends through the years. I will cherish my time getting to know you. I wish you all the best. This was not an easy decision to make. The cost to keep the communities running has gotten to the point where it's just too expensive. Security certificates, hosting cost, software renewals and everything else has increased threefold. While costs are up ad revenue is down. It's no longer viable to keep things running.

    All sites will be turned off on Thursday 30 November 2023. If you are interested in acquiring any of the websites I own you can Email Schwarz Network.

Simple (I hope) c++ question - cout an object of a user defined class

K

KeithLovell

Guest
I am not sure if this is the right forum for this question but it is the nearest that I have been able to find.

This code was adapted from code supplied in the book c++ for dummies. I would like to be able to output the student id number in the cout statements in main() but cannot figure out how to make it compile (using Visual Studio)

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int nextStudentId = 1000; // first valid student id
class StudentId
{
public:
// default constructor assigns student-ids sequentially
StudentId()
{
value = nextStudentId++;
cout << "Take next student id " << value << endl;
}
// int constructor allows user to assign id
StudentId(int id)
{
value = id;
cout << "Assign student id " << value << endl;
};
~StudentId()
{
cout << "Destructing student id " << value << endl;
}
protected:
int value;
};

class Student
{
public:
Student(const char* pName, int ssId)
: name(pName), id(ssId)
{
cout << "Constructing student " << pName << endl;
name = pName;
semesterHours = 0;
gpa = 0.0;
StudentId id(ssId);
}
Student(const char* pName)
// : name(pName), id(ssId)
{
cout << "Constructing student " << pName << endl;
name = pName;
semesterHours = 0;
gpa = 0.0;
// StudentId id;
}
~Student()
{
cout << "Destructing student " << name << endl;
}
public:
string name;
int semesterHours;
double gpa;
StudentId id;
};


int main(int nNumberofArgs, char* pszArgs[])
{
// create a couple of students
cout << "Next student id " << nextStudentId << endl;
Student* pS = new Student("Jack", 1234);

cout << "This mesage from main after Jack " << pS->name << *(pS->id) << endl; // would like to add the student id here.

Student* pS2 = new Student("Scruffy");
cout << "This message from main after Scruffy " << pS2->name << endl; // and here

delete pS;
delete pS2;
cout << "Next student id " << nextStudentId << endl;



// wait until user is ready before terminating program
// to allow user to see the program results
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}


Can anyone guide me?

Continue reading...
 
Top Bottom