0

Write a program to implement pointer to object in a class TRAIN. Train_Number , Train_Name, Arrival_Hr ,Arrival_Min, TimeDiff() are members in class. Member function TimeDiff() is used to find the time difference between Arrival Time (Arrival_Hr and Arrival_Min) and Reached Time ( New given Hr and Min for late arrival) and display the calculated time difference of the specified train. Use pointer to array of objects for different trains.

Is this program the correct answer to the question? I'm asking because I don't know what "Use a pointer to array of objects for different trains" means.

This is the code that I came up with:

#include <iostream>

using namespace std;

class TRAIN{
    public: int Train_Number;
    public: string Train_Name;
    int Arrival_Hr;
    int Arrival_Min;
    TRAIN(int Hr1,int Mn1, int Hr2, int Mn2) {
        Arrival_Hr = Hr2-Hr1;
        Arrival_Min = Mn2-Mn1;
        cout<<Arrival_Hr<<"Hr"<<Arrival_Min<<"min is the difference";
    }
};

int main(){
    TRAIN* ptr[10];
    ptr[0] = new TRAIN(2,30,4,40);
    ptr[1] = new TRAIN(1,20,5,30);
    ptr[0]->Train_Number = 100;
    ptr[0]->Train_Name = "Jansadabti";
    cout<<ptr[0]->Train_Number;
    cout<<ptr[0]->Train_Name;
    return 0;
}
2
  • 1
    Here is a better answer: stackoverflow.com/questions/5887615/… Commented Jan 10, 2021 at 7:50
  • 1
    Right now you are using an array of pointers TRAIN* ptr[10];, but I think you are supposed to to use a pointer to a dynamically allocated array like Train *ptr = new TRAIN[10]; Commented Jan 10, 2021 at 8:08

3 Answers 3

4

The program is a good start, but as-is it does not correctly address the things the question asks for.

You are missing the TimeDiff() method. What you have put into the TRAIN constructor is supposed to be in the TimeDiff() method instead.

The question asks for a “pointer to array of objects”, but you are using an “array of pointers to objects” instead.

Try something more like this:

#include <iostream>
using namespace std;

class TRAIN{
    public:
        int Train_Number;
        string Train_Name;
        int Arrival_Hr;
        int Arrival_Min;

        int TimeDiff(int Reached_Hr, int Reached_Min) const {
            int a_mins = (Arrival_Hr * 60) + Arrival_Min;
            int r_mins = (Reached_Hr * 60) + Reached_Min;
            return r_mins - a_mins;
        }
};

int main() {
    TRAIN* trains = new TRAIN[10];

    trains[0].Train_Number = 100;
    trains[0].Train_Name = "Jansadabti";
    trains[0].Arrival_Hr = 2;
    trains[0].Arrival_Min = 30;

    // populate other trains as needed...

    cout << trains[0].Train_Number << " " << trains[0].Train_Name << ", Time Difference: " << trains[0].TimeDiff(4, 40) << " minute(s)";

    delete[] trains;

    return 0;
}

Sign up to request clarification or add additional context in comments.

5 Comments

There are multiple errors in this code. The-> operator cannot be used with non-pointer types. trains is a pointer but not trains[0] and other members in the array so the . operator has to be used instead. Also, int r_mins = (Reached_Hr * 60) + Reached_Min); has an extra trailing )
@AmalK and it doesn't discuss the old-fashioned usage of raw new and delete. But still it has the most votes...
@AmalK fixed, thanks. They were stupid copy/paste errors.
@JHBonarius the alternative would be to use std::vector, but given that this looks like it is a homework assignment, chances are high that std::vector won’t be allowed.
@JHBonarius It's sad that concepts like smart pointers are seldom covered in most courses. Probably, because like other modern features, it is provided as a library rather than language-level constructs.
2

Many answers, but nobody is suggesting to use std::vector.

You're leaking memory. There's no deletes to your news. In modern C++, we would use smart pointers, i.e. std::unique_ptr<Train> trains[10], which is an array of smart pointers. And more logically, we would use a pointer to a dynamically allocated array: std::unique_ptr<Train[]> trains(new Train[10]). However, much better would be to use std::vector<Train> trains.

Example

struct Time {
    int hour;
    int minute;
};

struct TimeSpan {
    int hours;
    int minutes;
};

TimeSpan operator- (Time const& lhs, Time const& rhs) {
    TimeSpan ts {
        lhs.hour - rhs.hour,
        lhs.minute - rhs.minute };
    if (ts.minutes < 0) {
        ts.minutes += 60;
        ts.hours -= 1;
    }
    // and need something for when hours < 0, i.e. 0:30 - 23:30
    // with the exception for the case that you actually want a negative timespan...
    return ts;
}

#include <iostream>
std::ostream& operator<< (std::ostream& os, TimeSpan const& ts) {
    os << ts.hours << " hours and " << ts.minutes << " minutes";
    return os;
}

#include <string>
struct Train {
    int number;
    std::string name;
    TimeSpan travelTime;

    Train(Time const& departure, Time const& arrival)
    : number{/*?*/1}
    , name{/*?*/"name"}
    , travelTime{arrival - departure} 
    {}
};

std::ostream& operator<< (std::ostream& os, Train const& train) {
    os << "Train nr. " << train.number
       << " named " << train.name
       << " has a travel time of " << train.travelTime;
    return os;
}

#include <vector>

int main(){
    std::vector<Train> trains;
    trains.emplace_back(Train{Time{2,30},Time{4,40}});
    trains.emplace_back(Train{Time{1,20},Time{5,30}});
    trains[0].number = 100;
    trains[0].name = "Jansadabti";
    
    for (auto const& train: trains) {
        std::cout << train << '\n';
    }
}

Comments

0

What you have used is an array of pointers to objects but the question says to use a pointer to an array of objects. I suppose this means the array has to be dynamically created as demonstrated below. Note that usually UPPERCASE names are usually used for constants, so I've changed the name to Train. Also, the purpose of a constructor is to initialize the members of a class, not to perform calculations. Use methods (TimeDiff()) for calculations:

#include <string>
#include <iostream>
class Train {
public: 
    int Train_Number;
    std::string Train_Name;
    int Arrival_Hr;
    int Arrival_Min;
    Train(int number, std::string name, int hr, int min) 
    :  Train_Number(number), Train_Name(name), Arrival_Hr(hr), Arrival_Min(min)  
    {
        //empty body since I have used a member initializer list
    }
    Train() {} //empty constructor to allow array creation
    void TimeDiff(int new_hr, int new_min, int& diff_hr, int& diff_min)
    {
        diff_hr = new_hr - Arrival_Hr;
        diff_min = new_min - Arrival_Min;
    }
    // Overloading << so that you can use Train objects with std::cout
    friend std::ostream& operator<<(std::ostream& out, Train train);
};

std::ostream& operator<<(std::ostream& out, Train train)
{
    out << "\nTrain No: " << train.Train_Number;
    out << "\nTrain Name: " << train.Train_Name;
    out << "\nArrival Time: " << train.Arrival_Hr << ":" << train.Arrival_Min;
    return out;
}
int main()
{
    Train* t_array;
    t_array = new Train[10]; // Dynamically allocates a dynamic array of size 10 and returns a pointer to the base address

    t_array[0].Train_Number = 100;
    t_array[0].Train_Name = "Jansadabti";
    t_array[0].Arrival_Hr = 2;
    t_array[0].Arrival_Min = 30;
    //OR
    t_array[0] = Train(100, "Jansadabti", 2, 30);

    int diff_hr, diff_min;

   
   std::cout << t_array[0] << std::endl; // Possible because << is overloaded
   std::cout << "New Time: " << 4 << ":" << 40 << std::endl;

   t_array[0].TimeDiff(4, 40, diff_hr, diff_min);
   std::cout << "Time Difference: " << diff_hr << "hr " << diff_min << "min ";
    
     delete[] t_array; // Always delete dynamically allocated memory.
    return 0;
}

If something is not clear, do let me know, I'll break it down for you. Also, try to not use using namespace std, it clutters the global namespace. At the end of the day, it's C++, where someone will always complain about your code not being optimal enough.

1 Comment

"Note that usually UPPERCASE names are usually used for constants" that's only a coding guideline. More used for C defines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.