Jump to content

learning classes and objects

- - - - -

  • Please log in to reply
20 replies to this topic

#1
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Hi :)

I'm going to learn classes and objects. Could you please translate the code below into the one which uses concept of classes and objects? It would be kind of you. Thank you.



// student_data_read_practice.cpp

// program which reads data of some students


#include <iostream>

#include <cstdlib>

#include <string>

#include <cstring>


using namespace std;


/////////////////////////////////////////////////////

struct Date {int d; string m; int y;};

////////////////////////////////////////////////////


/////////////////////////////////////////////////////

struct Student {int rollno; string sex; string name; float gpa; Date DoB;};

/////////////////////////////////////////////////////


Student read();

void prnt(Student dummystud);

char grade(float dummyGpa);


int main()

{

    Student stud[5];


	for(int i=0; i<5; i++)

	{

	    cout << "enter student #" << (i+1) << "'s details below:-" << endl;

		stud[i] = read();

		prnt(stud[i]);

		cout << endl << endl;

	}


	system("pause");

	return 0;

}


//-----------------------------------------------

// Student read() definition


Student read()

{

    Student stud;


    cout << "enter name: "; getline(cin, stud.name);

	cout << "enter roll number: "; cin >> stud.rollno;

	cout << "enter sex: "; cin >> stud.sex;

	cout << "enter date of birth (e.g. 01 Jan 2000) below:-" << endl;

	cout << "enter day: "; cin >> stud.DoB.d;

	cout << "enter month: "; cin >> stud.DoB.m;

	cout << "enter year: "; cin >> stud.DoB.y;

	cout << "enter GPA: "; cin >> stud.gpa;

	cin.ignore();


	return stud;

}


//-------------------------------------------------

// void prnt() definition


void prnt (Student dummystud)

{

    cout << "\n\n\n************************************\n\n\n";

	cout << "roll no.: " << dummystud.rollno << endl;

	cout << "name: " << dummystud.name << endl;

	cout << "sex: " << dummystud.sex << endl;

	cout << "date of birth: " << dummystud.DoB.d << "-" << dummystud.DoB.m << "-" << dummystud.DoB.y << endl;

	cout << "grade: " << grade(dummystud.gpa) << endl;

	cout << "\n\n\n************************************";

}


//-------------------------------------------------------------

// grade() definition


char grade(float dummyGpa)

{

    if (dummyGpa >= 3.5)

        return 'A';


	else if (dummyGpa >= 3.0)

        return 'B';


	else if (dummyGpa >= 2.0)

        return 'C';


    else

        return 'D';


}


//----------------------------------------------------


I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#2
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
So, you mean, change it so Student is a class, instead of a struct? And so all the Student related functions are in the class?
Latinamne loqueris?

#3
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
Assuming that IS what you mean, here is the code:
#include <iostream>

#include <cstdlib>

#include <string>

#include <cstring>


using namespace std;


/////////////////////////////////////////////////////

struct Date {int d; string m; int y;};

////////////////////////////////////////////////////


/////////////////////////////////////////////////////

class Student

{

	private:

		int rollno;

		string sex;

		string name;

		float gpa;

		Date DoB;


	public:

		void prnt();

		void read();

};

/////////////////////////////////////////////////////


char grade(float dummyGpa);


int main()

{

    Student stud[5];


	for(int i=0; i<5; i++)

	{

	    cout << "enter student #" << (i+1) << "'s details below:-" << endl;

		stud[i].read();

		stud[i].prnt();

		cout << endl << endl;

	}


	system("pause");

	return 0;

}


//-----------------------------------------------

// Student read() definition


void Student::read()

{

    Student stud;


    cout << "enter name: "; getline(cin, stud.name);

	cout << "enter roll number: "; cin >> rollno;

	cout << "enter sex: "; cin >> sex;

	cout << "enter date of birth (e.g. 01 Jan 2000) below:-" << endl;

	cout << "enter day: "; cin >> DoB.d;

	cout << "enter month: "; cin >> DoB.m;

	cout << "enter year: "; cin >> DoB.y;

	cout << "enter GPA: "; cin >> gpa;

	cin.ignore();

}


//-------------------------------------------------

// void prnt() definition


void Student::prnt()

{

    cout << "\n\n\n************************************\n\n\n";

	cout << "roll no.: " << rollno << endl;

	cout << "name: " << name << endl;

	cout << "sex: " << sex << endl;

	cout << "date of birth: " << DoB.d << "-" << DoB.m << "-" << DoB.y << endl;

	cout << "grade: " << grade(gpa) << endl;

	cout << "\n\n\n************************************";

}


//-------------------------------------------------------------

// grade() definition


char grade(float dummyGpa)

{

    if (dummyGpa >= 3.5)

        return 'A';


	else if (dummyGpa >= 3.0)

        return 'B';


	else if (dummyGpa >= 2.0)

        return 'C';


    else

        return 'D';


}


//----------------------------------------------------


Latinamne loqueris?

#4
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts

mebob said:

Assuming that IS what you mean, here is the code:
#include <iostream>

#include <cstdlib>

#include <string>

#include <cstring>


using namespace std;


/////////////////////////////////////////////////////

struct Date {int d; string m; int y;};

////////////////////////////////////////////////////


/////////////////////////////////////////////////////

class Student

{

	[COLOR="#FF0000"]private:[/COLOR]

		int rollno;

		string sex;

		string name;

		float gpa;

		Date DoB;


	[COLOR="#FF0000"]public:[/COLOR]

		void prnt();

		void read();

};

/////////////////////////////////////////////////////


char grade(float dummyGpa);


int main()

{

    Student stud[5];


	for(int i=0; i<5; i++)

	{

	    cout << "enter student #" << (i+1) << "'s details below:-" << endl;

		stud[i].read();

		stud[i].prnt();

		cout << endl << endl;

	}


	system("pause");

	return 0;

}


//-----------------------------------------------

// Student read() definition


void Student::read()

{

    Student stud;


    cout << "enter name: "; getline(cin, stud.name);

	cout << "enter roll number: "; cin >> rollno;

	cout << "enter sex: "; cin >> sex;

	cout << "enter date of birth (e.g. 01 Jan 2000) below:-" << endl;

	cout << "enter day: "; cin >> DoB.d;

	cout << "enter month: "; cin >> DoB.m;

	cout << "enter year: "; cin >> DoB.y;

	cout << "enter GPA: "; cin >> gpa;

	cin.ignore();

}


//-------------------------------------------------

// void prnt() definition


void Student::prnt()

{

    cout << "\n\n\n************************************\n\n\n";

	cout << "roll no.: " << rollno << endl;

	cout << "name: " << name << endl;

	cout << "sex: " << sex << endl;

	cout << "date of birth: " << DoB.d << "-" << DoB.m << "-" << DoB.y << endl;

	cout << "grade: " << grade(gpa) << endl;

	cout << "\n\n\n************************************";

}


//-------------------------------------------------------------

// grade() definition


char grade(float dummyGpa)

{

    if (dummyGpa >= 3.5)

        return 'A';


	else if (dummyGpa >= 3.0)

        return 'B';


	else if (dummyGpa >= 2.0)

        return 'C';


    else

        return 'D';


}


//----------------------------------------------------


Thanks a lot, Bob (I hope I have it right). That is what I exactly meant! :)

I have some follow-on queries. Please help me with them. They can help me a lot to understand this new concept. And please keep it simple! :)

1: What do the words "private" and "public" do there?

2: I see you haven't included the "grade()" function inside the class. Any special reason? Is it so because it returns a value? Can't we include functions inside the class which return values? Is there any way to get the grade() function, like by changing its code etc?

3: Okay. The functions included inside the class are called member functions and they go like this AnyClass::AnyFunction(). I think you can merge this question with #2. Can class member function also take arguments?

4: Can't we create a structure such as Date which I used in the original code inside a class?

5: I have seen somewhere a member function written as:
public:

    void print() const;
What does "const" signify here?


I understand it takes a lot to help someone with these things. I'm much obliged for your help and your time.

Best wishes
Jackson
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#5
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
1. Members (functions and variables) declared under "public" can be accessed outside the class, whereas ones declared under "private" cannot. In the case of that class, you would not be able to access those variables from in the main function, but you can access it from a function from within the class.

2. No particular reason, I just didn't think it was necessary. You can return values from class members. Other than the fact that they are members of a class, they are exactly the same as any other function.

3. Yes, they can take arguments. It just wasn't necessary for this class.

4. Sorry, I don't understand what you are asking.

5. I don't know about that one.

Don't worry, I really don't have anything important to do (besides homework of course) :D

And my actual name is Collin, my online name is just something I made up.

Edited by mebob, 25 September 2011 - 08:03 AM.

Latinamne loqueris?

#6
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
4. Yes we can nest classes/structures inside classes. Also, we can write code inside classes, that's called inline code but is not recommended since this way compiler can not optimize code for you. Some say as a general rule of thumb, you shouldn't inline more than 2-5 lines.
class Student {
    public:
        // code...

    private:
        class Date {
            public:
                Date(int day, int month, int year)
                    : d(day), m(month), y(year)
                {
                }

                int d;
                int m;
                int y;
        };  // note that this is only class definition, we don't have an instance yet

        Date date;
        std::string name;
        // etc...
};

// access example
void Student::print() const {
    std::cout << "Date: " << date.d << "." << date.m << "." << date.y << "\n";
}

5. That const keyword means that method will not change/modify any properties of that class. In case you change data in there, compiler will throw an error.
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#7
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Thank you very much, Collin.

The modified code is below and I do have some follow-on queries. Please someone help me with them.

1: I still really understand the use of the words "public" and "private". Could you please elaborate their use in the context of present code?

2: As you can say I have used structure Date for member variable DoB. Using this structure the date would be be in this format, say, 27-Jan-2001. Is this possible to get the DoB in this format without using the structure Date? If this is possible the class in itself will be self-sufficient!

3: What would it mean if I had used this
void print() const;
?

4: What is a constructor? How do I build one?

Thank you your help and time.

Best regards
Jackson


// student_data_read_alterations.cpp

// program which reads data of some students using concept of class and object


#include <iostream>

#include <cstdlib>

#include <string>

#include <cstring>


using namespace std;


/////////////////////////////////////////////////////

[B]struct Date {int d; string m; int y;};[/B]

////////////////////////////////////////////////////


/////////////////////////////////////////////////////

class Student

{

	private:

		int rollno;

		string sex;

		string name;

		float gpa;

		[B]Date DoB;[/B]


	public:

		void prnt();

		void read();

		char grade(float dummyGpa);

};

/////////////////////////////////////////////////////


int main()

{

    Student stud[5];


	for(int i=0; i<5; i++)

	{

	    cout << "enter student #" << (i+1) << "'s details below:-" << endl;

		stud[i].read();

		stud[i].prnt();

		cout << endl << endl;

	}


	system("pause");

	return 0;

}


//-----------------------------------------------

// Student read() definition


void Student::read()

{

    Student stud;


    cout << "enter name: "; getline(cin, name);

	cout << "enter roll number: "; cin >> rollno;

	cout << "enter sex: "; cin >> sex;

	cout << "enter date of birth (e.g. 01 Jan 2000) below:-" << endl;

	cout << "enter day: "; cin >> DoB.d;

	cout << "enter month: "; cin >> DoB.m;

	cout << "enter year: "; cin >> DoB.y;

	cout << "enter GPA: "; cin >> gpa;

	cin.ignore();

}


//-------------------------------------------------

// void prnt() definition


void Student::prnt()

{

    cout << "\n\n\n************************************\n\n\n";

	cout << "roll no.: " << rollno << endl;

	cout << "name: " << name << endl;

	cout << "sex: " << sex << endl;

	cout << "date of birth: " << DoB.d << "-" << DoB.m << "-" << DoB.y << endl;

	cout << "grade: " << grade(gpa) << endl;

	cout << "\n\n\n************************************";

}


//-------------------------------------------------------------

// grade() definition


char Student::grade(float dummyGpa)

{

    if (dummyGpa >= 3.5)

        return 'A';


	else if (dummyGpa >= 3.0)

        return 'B';


	else if (dummyGpa >= 2.5)

        return 'C';


    else if (dummyGpa >= 2.0)

        return 'D';


    else

        return 'E';


}


//----------------------------------------------------


I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#8
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
2. It is possible, simply add day, month and year as properties to Student class. But it's more structured, and I'd say better, to make Date class. Date class can then even be used in other classes by simply making an object there, you don't have to write methods again, if you have/need them.

3. const at the end of function can only appear at member functions (methods). If you do not want to modify data (parameters) in functions, declare them as constants:
void fun(const Student& s) {
//...
}

4. Constructor or ctor is used, or rather called, when you create an object. It can be looked as a shortcut to initialize some data. You can have more than 1 ctor and the compiler will call the appropriate one.
class Student {
    public:
        Student(); //default ctor, no data provided
        Student(std::string& name); //create student object with a given name
        Student(int rollNumber, std::string& name, std::string& sex, float gpa, Date& date); //create student object will all data given
};
In the code above we have 3 constructors. Here's how you could use them:
int main() {
    Student a;  //calls default ctor
    Student b("John");  //calls 2nd one, since only std::string is given
    Student c(3, "Mary", "female", 4.95, Date(1, "Jan", 2000));  //3rd ctor, and using ctor for date (provided we have one)
}

A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#9
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
1. Generally, when a programmer creates a class, he doesn't want people to have to access the variables in the class directly, but instead would like people to use his functions to indirectly access those variables. To enforce this, there are "public" and "private" keywords that do or don't (respectively) allow access to something declared in the class from outside of it. So, if you declare a variable/function as public, it can be accessed through any instance of the said class. However, if you were to declare a variable/function as private, it could only be accessed through publicly-declared functions. So, for any data that shouldn't be accessed by somebody using your class, but only from the class's member functions, declare that data under the "private:" keyword. For any other stuff that SHOULD be accessible by a user of your class, declare under "public:".
Latinamne loqueris?

#10
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
There is also a protected: label, to allow classes that inherit that specific class access to the protected variables or functions.

class foo {
   protected:
       void b(int);
};
 
void foo::b(int) {
  //...
}
 
class bar : public foo {
   bar() {
      b(2);
   }
};
Another silly feature of C++ is a friend function:

class foo {
   int bar, baz
   public:
     friend void doSomething(); // Declare doSomething as a friend of the class
};

void doSomething() {
  foo my_foo;
  foo.bar = 2; // Now you can do this even though it is private
}

It may be easier to look through some of the class tutorials to iron out your knowledge on classes:
Classes (I) - C++ Documentation
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#11
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Thank you very much, Dutchman, Collin, Alexander. Very kind of you.

1: Are class member variables made private by default? I mean if I don't use any of the keywords, i.e. "private", "public".

The code also has my embedded question there in red. Please help me with them. Thanks a lot.


// student_data_read_alterations.cpp

// program which reads data of some students using concept of class and object


#include <iostream>

#include <cstdlib>

#include <string>

#include <cstring>


using namespace std;


/////////////////////////////////////////////////////

struct Date {int d; string m; int y;};

////////////////////////////////////////////////////


/////////////////////////////////////////////////////

class Student

{

	private:

		int rollno;

		string sex;

		string name;

		float gpa; //you cannot do, say, "cout << stud[1].gpa;"

		Date DoB;


	public:

		void prnt();

		void read();

		char grade(float dummyGpa) const; /* [B][COLOR="#FF0000"]what does "const" do here? it is giving me an error. what do I do?[/COLOR][/B] */


    public:

        Student(int rollno, string& sex, string& name, float gpa, Date& DoB); /* [B][COLOR="#FF0000"]unsuccessfully trying  to build a constrcutor, where I go wrong?[/COLOR][/B] */


// [B][COLOR="#FF0000"]why am I supposed to use "&"?[/COLOR][/B]

};

/////////////////////////////////////////////////////


const int L = 2;


int main()

{

    Student stud[L]; int i;


	for(i=0; i<L; i++)

	{

	    cout << "enter student #" << (i+1) << "'s details below:-" << endl;

		stud[i].read();

		stud[i].prnt();

		cout << endl << endl;

	}


	/* this cannot be executed because "gpa" is

    private, "cout << stud[1].gpa << endl;" */


    cout << stud[1].gpa.read() << endl;// [B][COLOR="#FF0000"]how do I access the GPA of stud[1]?[/COLOR][/B]


	system("pause");

	return 0;

}


//-----------------------------------------------

// Student read() definition


void Student::read()

{

    Student stud;


    cout << "enter name: "; getline(cin, name);

	cout << "enter roll number: "; cin >> rollno;

	cout << "enter sex: "; cin >> sex;

	cout << "enter date of birth (e.g. 01 Jan 2000) below:-" << endl;

	cout << "enter day: "; cin >> DoB.d;

	cout << "enter month: "; cin >> DoB.m;

	cout << "enter year: "; cin >> DoB.y;

	cout << "enter GPA: "; cin >> gpa;

	cin.ignore();

}


//-------------------------------------------------

// void prnt() definition


void Student::prnt()

{

    cout << "\n\n\n************************************\n\n\n";

	cout << "roll no.: " << rollno << endl;

	cout << "name: " << name << endl;

	cout << "sex: " << sex << endl;

	cout << "date of birth: " << DoB.d << "-" << DoB.m << "-" << DoB.y << endl;

	cout << "grade: " << grade(gpa) << endl;

	cout << "\n\n\n************************************";

}


//-------------------------------------------------------------

// grade() definition


char Student::grade(float dummyGpa)

{

    if (dummyGpa >= 3.5)

        return 'A';


	else if (dummyGpa >= 3.0)

        return 'B';


	else if (dummyGpa >= 2.5)

        return 'C';


    else if (dummyGpa >= 2.0)

        return 'D';


    else

        return 'E';

}


//----------------------------------------------------


List of Errors:

In function 'int main()':|

41|error: no matching function for call to 'Student::Student()'|

32|note: candidates are: Student::Student(int, std::string&, std::string&, float, Date&)|

17|note:                 Student::Student(const Student&)|

22|error: 'float Student::gpa' is private|

54|error: within this context|

54|error: request for member 'read' in 'stud[1].Student::gpa', which is of non-class type 'float'|

In member function 'void Student::read()':|

65|error: no matching function for call to 'Student::Student()'|

32|note: candidates are: Student::Student(int, std::string&, std::string&, float, Date&)|

17|note:                 Student::Student(const Student&)|

95|error: prototype for 'char Student::grade(float)' does not match any in class 'Student'|

28|error: candidate is: char Student::grade(float) const|

||=== Build finished: 7 errors, 0 warnings ===|


Edited by jackson6612, 26 September 2011 - 07:30 AM.

I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#12
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
1. You are missing const word here:
char Student::grade(float dummyGpa) [COLOR=#ff0000]const[/COLOR]

2. What error do you get for ctor?

3. & means reference. It's useful when passing other classes as function parameters because this doesn't create a copy of it, thus saving memory and it's faster.

4. You can't access GPA because it's private property. You can use set/get methods, or make it public.
A conclusion is where you got tired of thinking.
#define class struct    // All is public.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users