Karma
Karma

Reputation: 661

How to find acess a class-method of objects stored in c++ vector?

I am C++ noob, forgive me if this a simple question, I have been trying to solve this problem since past couple of days.

There exists a class called student which stores names, age and marks of a student. Each student's profile (age, name and marks is stored in a class). There are n students in a class hence , a vector<student*> is created, which stores the pointers to all the students profile in a class.

I want to print the values stored in the `vector I would really appreciate any hints!

#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;

class student{
private:
    string name;
    float marks;
    int age;
public:
    student(): name("Null"), marks(0),age(0){}
    student(string n, float m,int a): name(n), marks(m),age(a){}
    void set_name();
    void set_marks();
    void set_age();
    void get_name();
    void get_marks();
    void get_age();
};
void student::set_name(){
cout<<"Enter the name: ";
cin >> name;
}
void student::set_age(){
cout << "Enter the age: ";
cin >> age;
}
void student::set_marks(){
cout<<"Enter the marks ";
cin>> marks;
}
void student::get_name(){
    cout<<"Name: "<< name<<endl;
}
void student::get_age(){
    cout<<"Age: "<< age<<endl;
}

void student::get_marks(){
    cout<<"Marks: "<< marks<<endl;
}


int main() {
    int n;
    cout<<"Enter the number of students: ";
    cin >> n;
    vector <student*> library_stnd(n);
    for(int i=0;i<n;i++){
        student* temp = new student;
        temp->set_name();
        temp->set_age();
        temp->set_marks();
        library_stnd.push_back(temp);

    }


    for (auto ep: library_stnd){
         ep->get_age();
    }
    return(0);
}

Upvotes: 0

Views: 64

Answers (1)

Petar Petrovic
Petar Petrovic

Reputation: 414

vector <student*> library_stnd(n) create a vector of size n. Then in the first for loop library_stnd.push_back(temp) push temp to the end of library_stnd and does not change first n items.

The problem is the first n items in library_stnd is zero initialized[1] and dereferencing it in the second for loop is an undefined behavior.[2]

My suggestions is using either one of the following:

  1. vector <student*> library_stnd and library_stnd.push_back(temp)
  2. vector <student*> library_stnd(n) and library_stnd[i] = temp

Another suggestion

  1. vector<student> instead of vector<*student>, then for (auto& ep: library_stnd)
  2. '\n' instead of endl [3]
  3. double instead of float [4]

[1] - What is the default constructor for C++ pointer?

[2] - C++ standard: dereferencing NULL pointer to get a reference?

[3] - C++: "std::endl" vs "\n"

[4] - https://softwareengineering.stackexchange.com/questions/188721/when-do-you-use-float-and-when-do-you-use-double

Upvotes: 1

Related Questions