Professional Documents
Culture Documents
Object Oriented Programming (Oop) With C++ Class and Objects
Object Oriented Programming (Oop) With C++ Class and Objects
Class: A class is a template definition consisting of attributes (or variables) and methods (or
functions) to present a particular type of objects.
Attributes / variables: Describe the properties that the objects should have.
Methods / functions: Describes or defines the actions / functions that those group of objects
should perform
object1.memberfunction_1(arguments);
Name of the object followed by a dot (.) operator
object2.memberfunction_1(arguments); followed by the function name and arguments
(if any)
object1.memberfunction_2();
object2.memberfunction_2();
Declare the class Define the member functions
#include <iostream> void Person::setName(string nm){
using namespace std; name = nm;
}
class Person {
void Person::setAge(double ag){
private: age = ag;
string name; }
double age;
string Person::getName(){
public: return name;
void setName(string nm); }
void setAge(double ag);
double Person::getAge(){
string getName(); return age;
double getAge(); }
};
Create objects of the class and access the member variables and functions
int main()
{
// Creating objects of person class
Person p1;
Person p2;
p2.setName("Birbal");
p2.setAge(65);
cout << "P1 name: " << p1.getName() << endl << " P1 age: " << p1.getAge() << endl;
cout << "P2 name: " << p2.getName() << endl << " P2 age: " << p2.getAge();
}
ACCESS MODIFIERS – FOR MEMBER VARIABLES AND FUNCTIONS
For each instance (i.e., object) of the class, memory is allocated to only its
member variables.
Each instance of the class doesn't get it's own copy of the member function. All
instances share the same member function code.
What will be the output of the following program?
- Output and Error Tracing
WRITE ANOTHER TWO MEMBER FUNCTIONS TO RETRIEVE THE STUDENT ID AND NAME.
FINALLY CREATE THREE STUDENT OBJECTS TO STORE AND PRINT THEIR DATA IN MAIN FUNCTION.
#include <iostream>
#include<string>
using namespace std;
class Student {
int studentId;
string studentName;
Create a class called Rectangle. A rectangle should have height and width to describe it. Write
appropriate methods to set and get the height and width of a rectangle. Additionally, write a method
to calculate area of a rectangle.
Now create two rectangle objects in the main function. Set their height and width. Then print the area
of the rectangle which has larger area between the two.
Submission detail:
- Email attachment (.txt file)
- Email Subject: assignment2_PL2
- Write your name, id and section in the email body