Unit 3 - Classes and Objects
Unit 3 - Classes and Objects
OBJECTS
Review of Structures
◦Structures are user defined derived data types
◦Structures, unlike arrays, can hold different data types at
the same time
◦ Declaration syntax: struct structName
{
data_type var1;
data_type var2;
………
}; Prepared by Sherin Joshi
Review of Structures
◦The declaration is usually made outside the main body
◦eg: struct Person
{
int roll;
float weight;
char gender;
string name;
}; //to create variables in declaration → }p1,p2;
Prepared by Sherin Joshi
Review of Structures
◦Syntax to create structure variable: structName strVar;
◦Then, by the help of the dot (.) operator, any member
of the structure can be accessed
◦Syntax: strVar.var1 = someValue;
◦eg: struct Person p1;
p1.roll = 15;
#include <iostream>
using namespace std;
class Student
{
private:
int roll;
char name[20];
◦eg: obj1.getname( );
objPerson.name;
class Student
{
private:
int roll;
int age;
int marks;
class Student
{
private:
int roll;
string name;
Prepared by Sherin Joshi
public:
void setvalues( ) {
cout << endl << “Enter roll number: ”;
cin >> roll;
cout << endl << “Enter name: ”;
cin.ignore( );
getline(cin, name);
}
void getvalues( ) {
cout << endl << roll << “ , ” << name;
}
}; Prepared by Sherin Joshi
int main( )
{
Student s; //object of class Student
Student *sptr; //pointer to Student
sptr = &s;
sptr -> setvalues( ); //same as: s.setvalues( );
//cout << sptr -> roll; ----------- error
sptr -> getvalues( );
return 0;
}