0% found this document useful (0 votes)
21 views

LECTURE 6 - Structures, Classes and Objects

Uploaded by

lyleholst
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

LECTURE 6 - Structures, Classes and Objects

Uploaded by

lyleholst
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1

Virtual Classes Notes

ACADEMIC PROGRAMME: BSCS COMPUTER SCIENCE


COURSE CODE AND TITLE: BSCS 205: INTRODUCTION TO OOP
LECTURER’S NAME: PHILIP BITTOK
LECTURER’S CONTACTS: Phone No.: 0723683409 Email: [email protected]

Strucures, Classes and Objects


Expected Learning Outcomes:
By the end of this lesson, you should be able to:
i. C++ Structures
ii. Structure of a class
iii. How to instantiate objects

Structures in C++
• Structure is a collection of variables of different data types under a single name.
• It is similar to a class in that, both holds a collecion of data of different data types.
• You might want to store information about a student: Their name, reg_number, course, and
county
• One way to do this would be to create different variables: name, reg_number, course, and
county to hold all this information
• One problem with this is that if you would like to store information about multiple students,
you would create different variables for each person: name1, reg_number1, course1, county1
etc
• This approach would be messy and there would be relations between variables which add to the
mess
• A better approach would be to have a collection of all related information under a single name
Student and use for every other student
• The code will look more cleaner, and readable
• This collection of related information under a single name Student is called a structure

How to declare a structure in C++


• The struct keyword is used to define a structure followed by the identifier (name of identifier)
• Then inside the curly braces, you can declare one or more members (declare variables inside
curly braces) of that structure.
struct Student
{
float reg_number;
char name [50];
int age;
char course [30];
};
• Here, a structure Person is defined with 4 members: name, reg_number, county, and course
Page 1 of 15
2
Virtual Classes Notes

• When a structure is created, no memory is allocated.


• The structure definition is only the blueprint for the creating of variables.
• You can imagine it as a datatype.
• When you define an integer as below:
int age;
• The int specifies that the age can hold integer elements only
• The same way, structure definition only specifies what property a structure variable holds when
it is defined
• Note: Remember to end the declaration with a semicolon (;)

How to define structure variable


• Once you declare a structure person as above. You can define a structure variable as:
Student alice;
• Here, a structure variable alice is defined which is of type structure Person.
• When structure variable is defined, only then the required memory is allocated by the compiler.
• Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes, memory of
int is 4 bytes and memory of char is 1 byte.
• Hence, 88 bytes of memory is allocated for structure variable bill.

How to Access Members of a Structure


• The members of structure variable is accessed using a dot (.) operator.
• Suppose, you want to access age of structure variable alice and assign it 20 to it.
• You can perform this task by using following code below:
alice.age = 20;

Example: C++ Structure


#include<iostream>
using namespace std;
struct Student
{
float reg_number;
int age;
char name [50];
char course[30];
};
int main()
{
Student s1;
cout<<"Enter full name: ";
cin.get(s1.name, 50);
cout<<"Enter age: ";
cin>>s1.age;
cout<<"Enter your registration number: ";
cin>>s1.reg_number;
cout<<"Enter your course: ";
cin.get(s1.course, 30);
cout<<"\nDisplaying information ......."<<endl;
cout<<"Name: "<<s1.name<<endl;
Page 2 of 15
3
Virtual Classes Notes

cout<<"Registration Number: "<<s1.reg_number<<endl;


cout<<"Age: "<<s1.age<<endl;
cout<<"Course: "<<s1.course<<endl;
return 0;
}

Classes
A class is an expanded concept of a data structure: instead of holding only data, it can hold both data
and functions. An object is an instantiation of a class. In terms of variables, a class would be the type,
and an object would be the variable.
Classes are generally declared using the keyword class, with the following format:

Where class_name is a valid identifier for the class, object_names is an optional list of names for
objects of this class. The body of the declaration can contain members, that can be either data or
function declarations, and optionally access specifiers.
All is very similar to the declaration on data structures, except that we can now include also functions
and members, but also this new thing called access specifier. An access specifier is one of the
following three keywords: private, public or protected. These specifiers modify the access rights that
the members following them acquire:
• private members of a class are accessible only from within other members of the same class or from
their friends.
• protected members are accessible from members of their same class and from their friends, but also
from members of their derived classes.
• Finally, public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its
members. Therefore, any member that is declared before one other class specifier automatically has
private access. For example:

Page 3 of 15
4
Virtual Classes Notes

Declares a class (i.e., a type) called CRectangle and an object (i.e., a variable) of this class called rect.
This class contains four members: two data members of type int (member x and member y) with
private access (because private is the default access level) and two member functions with public
access: set_values() and area(), of which for now we have only included their declaration, not their
definition.
Notice the difference between the class name and the object name: In the previous example,
CRectangle was the class name (i.e., the type), whereas rect was an object of type CRectangle. It is the
same relationship int and a have in the following declaration:

where int is the type name (the class) and a is the variable name (the object).
After the previous declarations of CRectangle and rect, we can refer within the body of the program to
any of the public members of the object rect as if they were normal functions or normal variables, just
by putting the object's name followed by a dot (.) and then the name of the member. All very similar to
what we did with plain data structures before. For example:

The only members of rect that we cannot access from the body of our program outside the class are x
and y, since they have private access and they can only be referred from within other members of that
same class. Here is the complete example of class CRectangle:

Page 4 of 15
5
Virtual Classes Notes

The most important new thing in this code is the operator of scope (::, two colons) included in the
definition of set_values(). It is used to define a member of a class from outside the class definition
itself.
You may notice that the definition of the member function area() has been included directly within the
definition of the CRectangle class given its extreme simplicity, whereas set_values() has only its
prototype declared within the class, but its definition is outside it. In this outside declaration, we must
use the operator of scope (::) to specify that we are defining a function that is a member of the class
CRectangle and not a regular global function.
The scope operator (::) specifies the class to which the member being declared belongs, granting
exactly the same scope properties as if this function definition was directly included within the class
definition. For example, in the function set_values() of the previous code, we have been able to use the
variables x and y, which are private members of class CRectangle, which means they are only
accessible from other members of their class.
The only difference between defining a class member function completely within its class or to include
only the prototype and later its definition, is that in the first case the function will automatically be
considered an inline member function by the compiler, while in the second it will be a normal (not-
inline) class member function, which in fact supposes no difference in behavior.
Members x and y have private access (remember that if nothing else is said, all members of a class
defined with keyword class have private access). By declaring them private we deny access to them
from anywhere outside the class. This makes sense, since we have already defined a member function
to set values for those members within the object: the member function set_values(). Therefore, the
rest of the program does not need to have direct access to them. Perhaps in a so simple example as this,
Page 5 of 15
6
Virtual Classes Notes

it is difficult to see an utility in protecting those two variables, but in greater projects it may be very
important that values cannot be modified in an unexpected way (unexpected from the point of view of
the object).
One of the greater advantages of a class is that, as any other type, we can declare several objects of it.
For example, following with the previous example of class CRectangle, we could have declared the
object rectb in addition to the object rect:

In this concrete case, the class (type of the objects) to which we are talking about is CRectangle, of
which there are two instances or objects: rect and rectb. Each one of them has its own member
variables and member functions.

Notice that the call to rect.area() does not give the same result as the call to rectb.area(). This is
because each object of class CRectangle has its own variables x and y, as they, in some way, have also
their own function members set_value() and area() that each uses its object's own variables to operate.
That is the basic concept of object-oriented programming: Data and functions are both members of the
object. We no longer use sets of global variables that we pass from one function to another as
parameters, but instead we handle objects that have their own data and functions embedded as
members. Notice that we have not had to give any parameters in any of the calls to rect.area or
rectb.area. Those member functions directly used the data members of their respective objects rect and
rectb.

Page 6 of 15
7
Virtual Classes Notes

C++ Objects
• When a class is defined, only the specification for the object is defined; no memory
or storage is allocated.
• To use the data and access functions defined in the class, we need to create objects.
• Syntax to Define Object in C++


• We can create objects of Room class (defined in the above example) as follows:


• Here, two objects room1 and room2 of the Room class are created in
sampleFunction().
• Similarly, the objects room3 and room4 are created in main().
• As we can see, we can create objects of a class in any function of the program. We
can also create objects of a class within the class itself, or in other classes.
• Also, we can create as many objects as we want from a single class.
C++ Access Data Members and Member Functions

• We can access the data members and member functions of a class by using a .
(dot) operator. For example,
• This will call the calculateArea() function inside the Room class for object
room2.


• Similarly, the data members can be accessed as:


• In this case, it initializes the length variable of room1 to 5.5.

Example 2 Classes and Objects


// Program to illustrate the working of
// objects and class in C++ Programming
#include <iostream>
using namespace std;
Page 7 of 15
8
Virtual Classes Notes

// create a class
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
// create object of Room class
Room room1;
// assign values to data members
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
// calculate and display the area and volume of the room
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() <<
endl;
return 0;
}

• In this program, we have used the Room class and its object room1 to calculate the
area and volume of a room.
• In main(), we assigned the values of length, breadth, and height with the code:
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

Class with private members


• We then called the functions calculateArea() and calculateVolume() to perform the
necessary calculations.
• Note the use of the keyword public in the program. This means the members are
public and can be accessed anywhere from the program.
• As per our needs, we can also create private members using the private keyword.
• The private members of a class can only be accessed from within the class. For
example,
Page 8 of 15
9
Virtual Classes Notes

class Test {
private:
int a;
void function1() { }
public:
int b;
void function2() { }
}

• Here, a and function1() are private. Thus they cannot be accessed from outside the
class.
• On the other hand, b and function2() are accessible from everywhere in the program.
• // Program to illustrate the working of
• // public and private in C++ Class
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
// function to initialize private variables
void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}
double calculateArea() {
return length * breadth;
}
double calculateVolume() {

Page 9 of 15
10
Virtual Classes Notes

return length * breadth * height;


}
};
int main() {
// create object of Room class
Room room1;
// pass the values of private variables as arguments
room1.initData(42.5, 30.8, 19.2);
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() <<
endl;
return 0;
}
• The above example is nearly identical to the first example, except that the class
variables are now private.
• Since the variables are now private, we cannot access them directly from main().
Hence, using the following code would be invalid:
// invalid code
obj.length = 42.5;
obj.breadth = 30.8;
obj.height = 19.2;
• Instead, we use the public function initData() to initialize the private variables via
the function parameters double len, double brth, and double hgt.

Constructors and Destructors


Objects generally need to initialize variables or assign dynamic memory during their process of
creation to become operative and to avoid returning unexpected values during their execution. For
example, what would happen if in the previous example we called the member function area() before
having called function set_values()? Probably we would have gotten an undetermined result since the
members x and y would have never been assigned a value.
Page 10 of 15
11
Virtual Classes Notes

In order to avoid that, a class can include a special function called constructor, which is automatically
called whenever a new object of this class is created. This constructor function must have the same
name as the class, and cannot have any return type; not even void.
We are going to implement CRectangle including a constructor:

As you can see, the result of this example is identical to the previous one. But now we have removed
the member function set_values(), and have included instead a constructor that performs a similar
action: it initializes the values of x and y with the parameters that are passed to it.
Notice how these arguments are passed to the constructor at the moment at which the objects of this
class are created:

Constructors cannot be called explicitly as if they were regular member functions. They are only
executed when a new object of that class is created.
You can also see how neither the constructor prototype declaration (within the class) nor the latter
constructor definition include a return value; not even void.
The destructor fulfills the opposite functionality. It is automatically called when an object is destroyed,
either because its scope of existence has finished (for example, if it was defined as a local object within
a function and the function ends) or because it is an object dynamically assigned and it is released
using the operator delete.
The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also
return no value.

Page 11 of 15
12
Virtual Classes Notes

The use of destructors is especially suitable when an object assigns dynamic memory during its
lifetime and at the moment of being destroyed we want to release the memory that the object was
allocated.

Static members
A class can contain static members, either data or functions.
Static data members of a class are also known as "class variables", because there is only one unique
value for all the objects of that same class. Their content is not different from one object of this class to
another.
For example, it may be used for a variable within a class that can contain a counter with the number of
objects of that class that are currently allocated, as in the following example:

Page 12 of 15
13
Virtual Classes Notes

In fact, static members have the same properties as global variables but they enjoy class scope. For that
reason, and to avoid them to be declared several times, we can only include the prototype (its
declaration) in the class declaration but not its definition (its initialization). In order to initialize a static
data-member we must include a formal definition outside the class, in the global scope, as in the
previous example:

Because it is a unique variable value for all the objects of the same class, it can be referred to as a
member of any object of that class or even directly by the class name (of course this is only valid for
static members):

These two calls included in the previous example are referring to the same variable: the static variable
n within class CDummy shared by all objects of this class.
Once again, I remind you that in fact it is a global variable. The only difference is its name and
possible access restrictions outside its class.
Just as we may include static data within a class, we can also include static functions. They represent
the same: they are global functions that are called as if they were object members of a given class.
They can only refer to static data, in no case to non-static members of the class, as well as they do not
Page 13 of 15
14
Virtual Classes Notes

allow the use of the keyword this, since it makes reference to an object pointer and these functions in
fact are not members of any object but direct members of the class.

Page 14 of 15
15
Virtual Classes Notes

Further E-Resource Readings


CE, E. 3IT87: OBJECT ORIENTED PROGRAMMING WITH C++ CREDITS–4 (LTP: 3, 0, 2).

Page 15 of 15

You might also like