3

let say i have a student class with a program class pointer for programEnrolled? how to i do the getter and setter and how do i access the member inside the programEnrolled (programName, programFees) through programEnrolled?

and when should i use a pointer function?

class clsStudent
{
private:
    string studentName;
    string studentID;
    clsProgram *programEnrolled;
};

class clsProgram{
private:
    string programName;
    double programFees;
    string programCode;
};
Synxis
  • 9,236
  • 2
  • 42
  • 64
Alexius Lim
  • 59
  • 1
  • 1
  • 9
  • 2
    I suggest you to read a C++ book, because it seems you lack basic knowledge. [Here is a list](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) of good books. – Synxis Nov 12 '13 at 12:51
  • 1
    geter/seter may be good practice in other languages but not in C++. You are exposing implementation details outside the class. Make your methods verbs that act on the object. – Martin York Nov 12 '13 at 12:54
  • @Loki Astari: if i dont use getter and setter methods, then how am i supposed to access the members as they are all private? – Alexius Lim Nov 12 '13 at 13:05
  • @Synxis: Yea, im reading some books on c++ programming. Still quite new to it. The thing is im not sure about class type pointer to another class type pointer. if you make clsProgram program1 points to clsProgram2, what about the programName, programFees in clsProgram1. Does clsProgram1.programName = clsProgram2.programName? – Alexius Lim Nov 12 '13 at 13:20
  • @AlexiusLim: I presume they are private for a reason (you don't want people to access them). So why do you want to gain access to them? If you have to pull data out of a class do some work and then put data back into the class then it is better to write a method that does that work inside the class. In this case I would have a method called `enroll()` that enrolls you into a program (does more than set the member `programEnrolled` it would probably also call the `enrollStudent()` method on the `Program` object) This also abstracts away the concept that currently you only enroll in one program. – Martin York Nov 12 '13 at 15:11

1 Answers1

4

Why you need pointers in your program at all? By the way here is an example:

class clsStudent
{
public:
   void setProgram(clsProgram *x) { programEnrolled=x; }
   clsProgram *getProgram() const { return programEnrolled; }

  ...
};

clsStudent student;
student.getProgram()->programName;
masoud
  • 55,379
  • 16
  • 141
  • 208
  • how about setting the programName from main? if i have create a clsProgram object in main then prompt the user to enter all the information. How to i set the object into the programEnrolled? – Alexius Lim Nov 12 '13 at 13:01