The CName
variable is only declared in the local scope of your constructor mehtod:
Student::Student(int amount)
{
AmtClass = amount;
string *CName; // <<<
pName = new string[AmtClass]; // <<< Just leaks memory, nothing else
}
You probably meant to have it being a class member variable. Also note there's no need for a string*
pointer or new
, just use a std::vector
instead:
class Student
{
private:
int AmtClass;
std::vector<std::string> > StudentNames;
public:
Student(int numStudents);
}
Student::Student(int numStudents)
: AmtClass(numStudents)
{
StudentNames.resize(AmtClass);
}
After this constructor was called, you can access StudentNames[i]
where i
is in the range of [0-AmtClass[, in subsequently called methods from your Student
class.
All of that said, this would also suggest to name your class Students
to reflect the intended plural semantics correctly.
Or even better, this should be named Class
holding a std::vector<std::shared_ptr<Student> >
, where Student
is supposed to have a std::string
member name
.
OK, here we go:
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
class Student {
private:
std::string name;
public:
Student(const std::string& name_) : name(name_) {}
const std::string& getName() const { return name; }
};
class Class {
private:
typedef std::vector<std::shared_ptr<Student>> SubscriptionList;
SubscriptionList students;
const unsigned int MaxSubscribers;
public:
Class(unsigned int maxSubscribers) : MaxSubscribers(maxSubscribers) {}
bool subscribe(std::shared_ptr<Student>& student) {
if(students.size() >= MaxSubscribers) {
return false; // Class is full, can't subscribe
}
// May be put additional checks here, to prevent multiple subscrptions
students.push_back(student);
return true; // Sucessfully subscribed the class
}
void unsubscribe(std::shared_ptr<Student>& student) {
SubscriptionList::iterator it = students.begin();
for(;it != students.end();++it) {
if(it->get() == student.get()) {
break;
}
}
students.erase(it);
}
void showSubscribedStudents(std::ostream& os) {
unsigned int i = 1;
for(SubscriptionList::iterator it = students.begin();
it != students.end();
++it, ++i) {
os << i << ". " << (*it)->getName() << std::endl;
}
}
};
int main()
{
unsigned int amount;
std::cin >> amount;
std::cin.ignore();
Class theClass(amount);
for(unsigned int i = 0; i < amount; i++)
{
std::string name;
std::getline(std::cin,name);
std::shared_ptr<Student> student(new Student(name));
theClass.subscribe(student);
}
theClass.showSubscribedStudents(std::cout);
}
Input:
5
John Doe
Jane Doe
Aldo Willis
Chuck Norris
Mia Miles
Output:
1. John Doe
2. Jane Doe
3. Aldo Willis
4. Chuck Norris
5. Mia Miles