SlideShare a Scribd company logo
1 of 17
Download to read offline
​ ​ ​yourvirtualclass.com
C++ for Beginners
Lesson 10 - Classes and Objects
Section 1: What is a Class?
- a class is a user-defined type
- just like a primitive type, a class restricts the values its data can hold
- a class enhances the data it contains by associating methods to manipulate them
Consider an int primitive:
int number = 12;
What if we needed to constrain the value of the int primitive to be less than 7. We would
have to write extra code to enforce the constraint:
int number = 7;
if (number > 6)
{
number = 6;
}
This would have to be repeated for each number:
int number = 7;
if (number > 6)
{
number = 6;
}
int number2 = 13;
if (number2 > 6)
{
number2 = 6;
}
It's very easy to make a mistake:
int number = 7;
if (number > 6)
{
number = 6;
}
int number2 = 13;
if (number2 < 6)
{
number = 6; // Oops! number2 is still 13!!
}
If we could define a new type that constrains the value of an
int primitive to be less than 7, we would avoid such errors :
Listing 1: IntLessThan7.cpp
#include <iostream>
class IntLessThan7
{
int value; // the data: an int primitive
public:
IntLessThan7(int arg1) // a method: the class constructor
{
value = arg1;
if (value > 6)
{
value = 6;
}
}
int getValue() // a method: an accessor
{
return value;
}
int main(int argc, char** argv)
{
IntLessThan7 number(12);
IntLessThan7 number2(13);
std::cout << “number = " + number.getValue());
Std::cout << "number2 = " + number2.getValue());
}
}
OUTPUT:
number = 6
number2 = 6
- We have created a class IntLessThan7 that expands the int
primitive data type by associating with a method (the class
constructor) that constrains its range
- Using class IntLessThan7it is impossible to create an int
whose value is greater than 6
Section 2: The Class Declaration
- a class declaration specifies the data and functions
present in the class
Class declarations have the following form:
class class_name
{
access_specifier_1:
variable_or_method_declaration_1;
access_specifier_2:
variable_or_method_declaration_2;
...
};
- a class declaration begins with the class keyword followed
by the class name followed by an open curly brace "{"
- data is specified using variable declarations
- the term "method" is used for functions specified within a class
- methods are specified using method (function) declarations
- the data and methods specified defined within a class
are called the class "members"
- the class declaration continues until the close curly brace "}"
and is followed by a semicolon
The following class declaration specifies a class called "Box"
whose data are three int primitives (length,width, and height) and no
methods. All three members have public access:
class Box
{
public:
int length;
int width;
int height;
};
Section 3: Objects
- a class declaration occupies no memory
- an object is an example (instance) of a class that contains all
data and methods specified in the class declaration
- objects occupy memory
An object declaration has the same form as a variable declaration:
int number; // declares variable "number" of primitive type int
Box toy; // declares an object "toy" of class Box
Object declaration syntax:
classname objectname;
Public members of an object can be referenced using the object name followed
by a dot "." followed by the member name
toy.length = 5;
std::cout << toy.length;
- the terms "instance variables" and "instance data" refer
to the class data created when an object is declared
- each object contains a separate copy of all instance variables
which is independent from that of any other object
Listing 2: BoxUsage.cpp
#include <iostream>
class Box
{
public:
int length;
int width;
int height;
};
int main()
{
Box toy; // declares an object "toy" of class Box
toy.length=5;
toy.width=4; // toy has its own copy of length, width and height
toy.height=3;
Box tools; // declares another object "tools" of class Box
tools.length=8;
tools.width=7; // tools has a separate copy of length, width and height
tools.height=6;
std::cout << "toy dimensions: " << toy.length << " "
<< toy.width << " " << toy.height << std::endl;
std::cout << "tools dimensions: " << tools.length << " "
<< tools.width << " " << tools.height << std::endl;
return 0;
}
LAB1​: Write a class called House whose data is its square feet, street address,
number of rooms, and number of occupants. Use a char array for the
street address. Create several Houses in your main program, set their data
to values, and print them out.
Section 4: Access
- the outside world should see only the members of a class with which
it needs to interact
- make these members public using the "public:" access specifier
- make all other members private using the "private:" access specifier
- access specifiers can occur on any line inside a class declaration
- the access remains in effect until overridden by another
- the default access is private
class Box2
{
int length; // length is private (default access)
public: // members that follow are public
int width; // width is public
int height; // height is also public
private: // members that follow are private
int height2; // height2 is private
public: // members that follow are public
private: // overrides previous access,
// members that follow are now private
int height3; // height3 is private
};
- instance data should ALWAYS be declared private
- prevents the outside world from:
1)- setting the data to erroneous values
2)- using the data incorrectly
3)- seeing proprietary data
Here is the Box class with correct access:
class Box
{
int length;
int width;
int height;
};
- all instance variables are private (default access)
- need to specify methods for the outside to interact
with the instance data
Section 5: Public Class Methods
- class methods enhance class data by manipulating it
- can read and modify all class data (private and public)
- public class methods can be called by the outside world
- provide an interface (instructions on how to use the class)
to callers (also known as "clients" of the class)
Most common design:
- provide a method to read (get) each instance variable
- return type of the method = type of instance variable
- method returns the instance variable
- method takes no arguments
- prefix name of method with "get"
- commonly referred to as a "getter"
int getLength() // getter for length instance variable
{
return length;
}
- provide a method to modify (set) each instance variable
- one formal parameter whose type = type of instance variable
- return type of the method is void
- method assigns formal parameter to instance variable
- prefix name of method with "set"
- commonly referred to as a "setter"
- the term "accessor" refers to a setter or getter
void setWidth(int w) // setter for width instance variable
{
width = w;
}
- ​ENCAPSULATION​:
- one of the key concepts in object oriented programming
- classes must keep instance data private and provide the accessors
necessary for clients
- allows large-scale maintainable software
- accessors can prevent instance data from being set to erroneous values
Let's say that for a box to fit into your car, its length must be 5 feet or less:
void setLength(int len) // setter for length instance variable
{
if ( len <= 5 )
{ // prevents setting length to a value
length = len; // greater than five feet
}
else
{
std::cout << "ERROR: length cannot be greater than 5" << std::endl;
}
}
Let's update the BoxUsage program to comply with encapsulation:
Listing 3: BoxEncapsulated.cpp
#include <iostream>
class Box
{
int length;
int width;
int height;
public:
int getLength() // getter for length instance variable
{
return length;
}
int getWidth() // getter for width instance variable
{
return width;
}
int getHeight() // getter for height instance variable
{
return height;
}
void setLength(int len) // setter for length instance variable
{
if ( len <= 5 )
{ // prevents setting length to a value
length = len; // greater than five feet
}
else
{
std::cout << "ERROR: length cannot be greater than 5" << std::endl;
}
}
void setWidth(int w) // setter for width instance variable
{
width = w;
}
void setHeight(int h) // setter for height instance variable
{
height = h;
}
};
int main()
{
Box toy;
toy.length=5; // ERROR: length instance variable is private
// use setter instead
toy.setLength(5);
toy.setWidth(4);
toy.setHeight(3);
Box tools;
tools.setLength(8); // erroneous value, length not set
tools.setLength(4); // good value, length updated
tools.setWidth(7);
tools.setHeight(6);
std::cout << "toy dimensions: " << toy.length; // ERROR: length instance variable is private
// use getter instead
std::cout << "toy dimensions: " << toy.getLength() << " "
<< toy.getWidth() << " " << toy.getHeight() << std::endl;
std::cout << "tools dimensions: " << tools.getLength() << " "
<< tools.getWidth() << " " << tools.getHeight() << std::endl;
return 0;
}
LAB2​: Make the data in the House from LAB1 private. Write setters and getters and call
them in the main program to populate and print the data.
Section 6: Class Header Files
- the Box class is getting quite large
- makes it harder to understand what the BoxEncapsulated main program is doing
- if we had a second main program (called BoxApp2.cpp)
- would have to copy the class declaration into BoxApp2.cpp
- would have to maintain two copies
SOLUTION:
- place the Box class declaration in header file Box.h
- include Box.h in both BoxEncapsulated.cpp and BoxApp2.cpp
Inlining​:
- when a method is DEFINED (its executable statements are listed) inside a class definition,
the method is inlined instead of called
- the contents of the method is copied to the caller at the point of call
- inlining makes an application needlessly large
class Box
{
...
public:
void setLength(int len)
{
if ( len <= 5 )
{
length = len;
}
}
...
};
int main() ​WHAT REALLY HAPPENS:
{
Box toy; Box toy;
toy.setLength(3); if (len <= 5) // no call occurs, method inlined
{
length = len;
}
SOLUTION:
- specify method DECLARATION in the class declaration
- place method DEFINITION in a .cpp file, which is compiled separatedly
Listing 4: Box.h
class Box
{
int length;
int width;
int height;
public:
int getLength(); // specify DECLARATIONS for each method
int getWidth(); // DEFINITIONS in Box.cpp
int getHeight();
void setLength(int len);
void setWidth(int w);
void setHeight(int h);
};
- note that iostream.h is not included in Box.h
- Needed in the DEFINITION of Box, not the DECLARATION
- NEVER include unnecessary header files in your own header files
- slows down your compilations
- this is an important point that is missed by MOST PROFESSIONAL
PROGRAMMERS!!
Section 7: Scope
- a scope is a region of a program
- variables only exist inside the scope in which they are declared
int quotient(int arg1, int arg2) // function quotient scope begins
{
int q = arg1/arg2; // variable q is local to function quotient
return q; // (has function quotient scope)
} // q disappears (goes out of scope)
int main()
{
int denominator = 5;
if ( denominator > 0) // if clause scope begins
{
int x = 10/denominator; // variable x is local to current if clause
std::cout << x << std::endl;
} // x disappears (goes out of scope)
return 0;
}
- class data exists only inside their class scope
- "::" is the C++ scope resolution operator
- use class_name:: to enter class_name scope from anywhere in your program
Listing 5: Box.cpp
#include <iostream> // iostream.h needed by Box DEFINITION
#include "Box.h" // include Box header file to obtain class DECLARATION
// specify non-standard file in double-quotes
// specify .h
int Box::getLength() // DEFINITION of the getLength() method of class Box
{ // Box:: enters the class Box scope
// inside getLength() definition (inside class Box scope)
return length; // can access class data
} // leaving class Box scope
int Box::getWidth()
{
return width;
}
int Box::getHeight()
{
return height;
}
void Box::setLength(int len)
{
if ( len <= 5 )
{
length = len;
}
else
{
std::cout << "ERROR: length cannot be greater than 5" << std::endl;
}
}
void Box::setWidth(int w)
{
width = w;
}
void Box::setHeight(int h)
{
height = h;
}
Listing 6: BoxEncapsulatedWithHeader.cpp
#include <iostream> // iostream.h needed by main program
#include "Box.h" // include Box header file to obtain class DECLARATION
int main()
{
Box toy;
toy.setLength(5);
toy.setWidth(4);
toy.setHeight(3);
Box tools;
tools.setLength(8); // erroneous value, length not set
tools.setLength(4); // good value, length updated
tools.setWidth(7);
tools.setHeight(6);
std::cout << "toy dimensions: " << toy.getLength() << " "
<< toy.getWidth() << " " << toy.getHeight() << std::endl;
std::cout << "tools dimensions: " << tools.getLength() << " "
<< tools.getWidth() << " " << tools.getHeight() << std::endl;
return 0;
}
Building the executable is a little more complex, but well worth it:
Compile the Box method definitions into a separate object file (.o) using -c compiler switch
g++ -c Box.cpp -o Box.o
Compile BoxEncapsulatedWithHeader.cpp into another object file
g++ -c BoxEncapsulatedWithHeader.cpp -o BoxEncapsulatedWithHeader.o
Link both object files into an executable
g++ BoxEncapsulatedWithHeader.o Box.o -o BoxEncapsulatedWithHeader
Execute:
​BoxEncapsulatedWithHeader
OUTPUT:
ERROR: length cannot be greater than 5
toy dimensions: 5 4 3
tools dimensions: 4 7 6
Listing 7: BoxApp2.cpp
#include <iostream>
#include "Box.h"
int main()
{
Box present;
present.setLength(10);
present.setLength(9);
present.setLength(8);
present.setLength(2);
present.setWidth(20);
present.setHeight(30);
std::cout << "present dimensions: " << present.getLength() << " "
<< present.getWidth() << " " << present.getHeight() << std::endl;
return 0;
}
Building the executable:
(no need to re-compile Box.cpp)
Compile BoxApp2.cpp into another object file
g++ -c BoxApp2.cpp -o BoxApp2.o
Link both object files into an executable
g++ BoxApp2.o Box.o -o BoxApp2
Execute:
BoxApp2
OUTPUT:
ERROR: length cannot be greater than 5
ERROR: length cannot be greater than 5
ERROR: length cannot be greater than 5
present dimensions: 2 20 30
- Our implementation of the Box class now supports multiple main programs
without any duplication of code
LAB3​: Write a class called Car with data for miles per gallon, make, and model.
Use char arrays for make and model. Make data private and provide setters
and getters. Place Car class declaration in file Car.h . Place Car class
implementation in file Car.cpp . Create a driver program called CarDriver.cpp.
Compile and link using g++ .
Section 8: Adding Other Methods to your Class
- classes can contain methods in addition to getters and setters
- methods which clients need to call must be public
- methods used internally should be private
Listing 8: Box.h
class Box
{
int length;
int width;
int height;
​bool lengthInRange(); ​ // private methods
​void printLengthError(); ​ // called only inside Box’s setLength() method
public:
int getLength();
int getWidth();
int getHeight();
void setLength(int len);
void setWidth(int w);
void setHeight(int h);
​ int computeVolume(); ​ // public method: client’s can call to compute Box’s volume
};
Listing 9: From Box.cpp
int Box::computeVolume()
{
return length * width * height;
}
Bool Box::lengthInRange(int len)
{
return len <= 5;
}
void Box::printLengthError()
{
std::cout << "ERROR: length cannot be greater than 5" << std::endl;
}
void Box::setLength(int len)
{
if ( ​lengthInRange(len)​ )
{
length = len;
}
else
{
​printLengthError();
}
}
Listing 10 : BoxApp3.cpp
#include <iostream>
#include "Box.h"
int main()
{
Box present;
present.setLength(10);
present.setLength(2);
present.setWidth(20);
present.setHeight(30);
std::cout << "present dimensions: " << present.getLength() << " "
<< present.getWidth() << " " << present.getHeight() << std::endl;
int volume = present.computeVolume();
std::cout << “present volume = “ << volume << std::endl;
return 0;
}
OUTPUT:
ERROR: length cannot be greater than 5
ERROR: length cannot be greater than 5
ERROR: length cannot be greater than 5
present dimensions: 2 20 30
volume = 1200
LAB4​: Add an occupancy() method to the House class from LABs 1 and 2 which
Returns the quotient of the number of rooms and the number of occupants.
Write a HouseDriver program and call House’s occupancy() method from it.
Copyright 2016 YourVirtualClass.com. All rights reserved.

More Related Content

What's hot

Mobile Email Security
Mobile Email SecurityMobile Email Security
Mobile Email Security
Rahul Sihag
 

What's hot (19)

Farhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd YearFarhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd Year
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
Unit3
Unit3Unit3
Unit3
 
Learn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & MethodsLearn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & Methods
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
Core java oop
Core java oopCore java oop
Core java oop
 
Python3
Python3Python3
Python3
 
java classes
java classesjava classes
java classes
 
MS.Net Interview Questions - Simplified
MS.Net Interview Questions - SimplifiedMS.Net Interview Questions - Simplified
MS.Net Interview Questions - Simplified
 
Only oop
Only oopOnly oop
Only oop
 
Structure in c#
Structure in c#Structure in c#
Structure in c#
 
Mobile Email Security
Mobile Email SecurityMobile Email Security
Mobile Email Security
 
C# Types of classes
C# Types of classesC# Types of classes
C# Types of classes
 
130614 sebastiano panichella - mining source code descriptions from develo...
130614   sebastiano panichella -  mining source code descriptions from develo...130614   sebastiano panichella -  mining source code descriptions from develo...
130614 sebastiano panichella - mining source code descriptions from develo...
 

Viewers also liked

內觀修行的起源
內觀修行的起源內觀修行的起源
內觀修行的起源
宏 恆
 

Viewers also liked (7)

Chempublish Kimya Dergisi Sayı 3
Chempublish Kimya Dergisi Sayı 3Chempublish Kimya Dergisi Sayı 3
Chempublish Kimya Dergisi Sayı 3
 
TUREB Magazin
TUREB MagazinTUREB Magazin
TUREB Magazin
 
Дайджест журнала "Дистрибуция и логистика" № 6, 2016
Дайджест журнала "Дистрибуция и логистика" № 6, 2016Дайджест журнала "Дистрибуция и логистика" № 6, 2016
Дайджест журнала "Дистрибуция и логистика" № 6, 2016
 
inovatif kimya dergisi sayi 1
inovatif kimya dergisi sayi 1inovatif kimya dergisi sayi 1
inovatif kimya dergisi sayi 1
 
inovatif kimya dergisi sayi 2
inovatif kimya dergisi sayi 2inovatif kimya dergisi sayi 2
inovatif kimya dergisi sayi 2
 
內觀修行的起源
內觀修行的起源內觀修行的起源
內觀修行的起源
 
The life of a Leo
The life of a LeoThe life of a Leo
The life of a Leo
 

Similar to ClassesandObjects

Assignment Examples Final 07 Oct
Assignment Examples Final 07 OctAssignment Examples Final 07 Oct
Assignment Examples Final 07 Oct
Sriram Raj
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-class
Deepak Singh
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
Jay Patel
 

Similar to ClassesandObjects (20)

Class and object
Class and objectClass and object
Class and object
 
OOP.ppt
OOP.pptOOP.ppt
OOP.ppt
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
Assignment Examples Final 07 Oct
Assignment Examples Final 07 OctAssignment Examples Final 07 Oct
Assignment Examples Final 07 Oct
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-class
 
OOP C++
OOP C++OOP C++
OOP C++
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
Exercises
ExercisesExercises
Exercises
 
Inheritance
Inheritance Inheritance
Inheritance
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 

ClassesandObjects

  • 1. ​ ​ ​yourvirtualclass.com C++ for Beginners Lesson 10 - Classes and Objects Section 1: What is a Class? - a class is a user-defined type - just like a primitive type, a class restricts the values its data can hold - a class enhances the data it contains by associating methods to manipulate them Consider an int primitive: int number = 12; What if we needed to constrain the value of the int primitive to be less than 7. We would have to write extra code to enforce the constraint: int number = 7; if (number > 6) { number = 6; } This would have to be repeated for each number: int number = 7; if (number > 6) { number = 6; } int number2 = 13; if (number2 > 6) { number2 = 6; } It's very easy to make a mistake:
  • 2. int number = 7; if (number > 6) { number = 6; } int number2 = 13; if (number2 < 6) { number = 6; // Oops! number2 is still 13!! } If we could define a new type that constrains the value of an int primitive to be less than 7, we would avoid such errors : Listing 1: IntLessThan7.cpp #include <iostream> class IntLessThan7 { int value; // the data: an int primitive public: IntLessThan7(int arg1) // a method: the class constructor { value = arg1; if (value > 6) { value = 6; } } int getValue() // a method: an accessor { return value; } int main(int argc, char** argv) { IntLessThan7 number(12); IntLessThan7 number2(13); std::cout << “number = " + number.getValue()); Std::cout << "number2 = " + number2.getValue()); } }
  • 3. OUTPUT: number = 6 number2 = 6 - We have created a class IntLessThan7 that expands the int primitive data type by associating with a method (the class constructor) that constrains its range - Using class IntLessThan7it is impossible to create an int whose value is greater than 6 Section 2: The Class Declaration - a class declaration specifies the data and functions present in the class Class declarations have the following form: class class_name { access_specifier_1: variable_or_method_declaration_1; access_specifier_2: variable_or_method_declaration_2; ... }; - a class declaration begins with the class keyword followed by the class name followed by an open curly brace "{" - data is specified using variable declarations - the term "method" is used for functions specified within a class - methods are specified using method (function) declarations - the data and methods specified defined within a class are called the class "members" - the class declaration continues until the close curly brace "}" and is followed by a semicolon The following class declaration specifies a class called "Box" whose data are three int primitives (length,width, and height) and no methods. All three members have public access: class Box {
  • 4. public: int length; int width; int height; }; Section 3: Objects - a class declaration occupies no memory - an object is an example (instance) of a class that contains all data and methods specified in the class declaration - objects occupy memory An object declaration has the same form as a variable declaration: int number; // declares variable "number" of primitive type int Box toy; // declares an object "toy" of class Box Object declaration syntax: classname objectname; Public members of an object can be referenced using the object name followed by a dot "." followed by the member name toy.length = 5; std::cout << toy.length; - the terms "instance variables" and "instance data" refer to the class data created when an object is declared - each object contains a separate copy of all instance variables which is independent from that of any other object Listing 2: BoxUsage.cpp #include <iostream> class Box { public: int length; int width; int height;
  • 5. }; int main() { Box toy; // declares an object "toy" of class Box toy.length=5; toy.width=4; // toy has its own copy of length, width and height toy.height=3; Box tools; // declares another object "tools" of class Box tools.length=8; tools.width=7; // tools has a separate copy of length, width and height tools.height=6; std::cout << "toy dimensions: " << toy.length << " " << toy.width << " " << toy.height << std::endl; std::cout << "tools dimensions: " << tools.length << " " << tools.width << " " << tools.height << std::endl; return 0; } LAB1​: Write a class called House whose data is its square feet, street address, number of rooms, and number of occupants. Use a char array for the street address. Create several Houses in your main program, set their data to values, and print them out. Section 4: Access - the outside world should see only the members of a class with which it needs to interact - make these members public using the "public:" access specifier - make all other members private using the "private:" access specifier - access specifiers can occur on any line inside a class declaration - the access remains in effect until overridden by another - the default access is private class Box2 { int length; // length is private (default access) public: // members that follow are public
  • 6. int width; // width is public int height; // height is also public private: // members that follow are private int height2; // height2 is private public: // members that follow are public private: // overrides previous access, // members that follow are now private int height3; // height3 is private }; - instance data should ALWAYS be declared private - prevents the outside world from: 1)- setting the data to erroneous values 2)- using the data incorrectly 3)- seeing proprietary data Here is the Box class with correct access: class Box { int length; int width; int height; }; - all instance variables are private (default access) - need to specify methods for the outside to interact with the instance data Section 5: Public Class Methods - class methods enhance class data by manipulating it - can read and modify all class data (private and public) - public class methods can be called by the outside world - provide an interface (instructions on how to use the class) to callers (also known as "clients" of the class) Most common design: - provide a method to read (get) each instance variable
  • 7. - return type of the method = type of instance variable - method returns the instance variable - method takes no arguments - prefix name of method with "get" - commonly referred to as a "getter" int getLength() // getter for length instance variable { return length; } - provide a method to modify (set) each instance variable - one formal parameter whose type = type of instance variable - return type of the method is void - method assigns formal parameter to instance variable - prefix name of method with "set" - commonly referred to as a "setter" - the term "accessor" refers to a setter or getter void setWidth(int w) // setter for width instance variable { width = w; } - ​ENCAPSULATION​: - one of the key concepts in object oriented programming - classes must keep instance data private and provide the accessors necessary for clients - allows large-scale maintainable software - accessors can prevent instance data from being set to erroneous values Let's say that for a box to fit into your car, its length must be 5 feet or less: void setLength(int len) // setter for length instance variable { if ( len <= 5 ) { // prevents setting length to a value length = len; // greater than five feet } else { std::cout << "ERROR: length cannot be greater than 5" << std::endl;
  • 8. } } Let's update the BoxUsage program to comply with encapsulation: Listing 3: BoxEncapsulated.cpp #include <iostream> class Box { int length; int width; int height; public: int getLength() // getter for length instance variable { return length; } int getWidth() // getter for width instance variable { return width; } int getHeight() // getter for height instance variable { return height; } void setLength(int len) // setter for length instance variable { if ( len <= 5 ) { // prevents setting length to a value length = len; // greater than five feet } else { std::cout << "ERROR: length cannot be greater than 5" << std::endl; } } void setWidth(int w) // setter for width instance variable { width = w; } void setHeight(int h) // setter for height instance variable {
  • 9. height = h; } }; int main() { Box toy; toy.length=5; // ERROR: length instance variable is private // use setter instead toy.setLength(5); toy.setWidth(4); toy.setHeight(3); Box tools; tools.setLength(8); // erroneous value, length not set tools.setLength(4); // good value, length updated tools.setWidth(7); tools.setHeight(6); std::cout << "toy dimensions: " << toy.length; // ERROR: length instance variable is private // use getter instead std::cout << "toy dimensions: " << toy.getLength() << " " << toy.getWidth() << " " << toy.getHeight() << std::endl; std::cout << "tools dimensions: " << tools.getLength() << " " << tools.getWidth() << " " << tools.getHeight() << std::endl; return 0; } LAB2​: Make the data in the House from LAB1 private. Write setters and getters and call them in the main program to populate and print the data. Section 6: Class Header Files - the Box class is getting quite large - makes it harder to understand what the BoxEncapsulated main program is doing - if we had a second main program (called BoxApp2.cpp)
  • 10. - would have to copy the class declaration into BoxApp2.cpp - would have to maintain two copies SOLUTION: - place the Box class declaration in header file Box.h - include Box.h in both BoxEncapsulated.cpp and BoxApp2.cpp Inlining​: - when a method is DEFINED (its executable statements are listed) inside a class definition, the method is inlined instead of called - the contents of the method is copied to the caller at the point of call - inlining makes an application needlessly large class Box { ... public: void setLength(int len) { if ( len <= 5 ) { length = len; } } ... }; int main() ​WHAT REALLY HAPPENS: { Box toy; Box toy; toy.setLength(3); if (len <= 5) // no call occurs, method inlined { length = len; } SOLUTION: - specify method DECLARATION in the class declaration - place method DEFINITION in a .cpp file, which is compiled separatedly Listing 4: Box.h class Box {
  • 11. int length; int width; int height; public: int getLength(); // specify DECLARATIONS for each method int getWidth(); // DEFINITIONS in Box.cpp int getHeight(); void setLength(int len); void setWidth(int w); void setHeight(int h); }; - note that iostream.h is not included in Box.h - Needed in the DEFINITION of Box, not the DECLARATION - NEVER include unnecessary header files in your own header files - slows down your compilations - this is an important point that is missed by MOST PROFESSIONAL PROGRAMMERS!! Section 7: Scope - a scope is a region of a program - variables only exist inside the scope in which they are declared int quotient(int arg1, int arg2) // function quotient scope begins { int q = arg1/arg2; // variable q is local to function quotient return q; // (has function quotient scope) } // q disappears (goes out of scope) int main() { int denominator = 5; if ( denominator > 0) // if clause scope begins { int x = 10/denominator; // variable x is local to current if clause std::cout << x << std::endl; } // x disappears (goes out of scope) return 0; }
  • 12. - class data exists only inside their class scope - "::" is the C++ scope resolution operator - use class_name:: to enter class_name scope from anywhere in your program Listing 5: Box.cpp #include <iostream> // iostream.h needed by Box DEFINITION #include "Box.h" // include Box header file to obtain class DECLARATION // specify non-standard file in double-quotes // specify .h int Box::getLength() // DEFINITION of the getLength() method of class Box { // Box:: enters the class Box scope // inside getLength() definition (inside class Box scope) return length; // can access class data } // leaving class Box scope int Box::getWidth() { return width; } int Box::getHeight() { return height; } void Box::setLength(int len) { if ( len <= 5 ) { length = len; } else { std::cout << "ERROR: length cannot be greater than 5" << std::endl; } } void Box::setWidth(int w)
  • 13. { width = w; } void Box::setHeight(int h) { height = h; } Listing 6: BoxEncapsulatedWithHeader.cpp #include <iostream> // iostream.h needed by main program #include "Box.h" // include Box header file to obtain class DECLARATION int main() { Box toy; toy.setLength(5); toy.setWidth(4); toy.setHeight(3); Box tools; tools.setLength(8); // erroneous value, length not set tools.setLength(4); // good value, length updated tools.setWidth(7); tools.setHeight(6); std::cout << "toy dimensions: " << toy.getLength() << " " << toy.getWidth() << " " << toy.getHeight() << std::endl; std::cout << "tools dimensions: " << tools.getLength() << " " << tools.getWidth() << " " << tools.getHeight() << std::endl; return 0; } Building the executable is a little more complex, but well worth it: Compile the Box method definitions into a separate object file (.o) using -c compiler switch g++ -c Box.cpp -o Box.o
  • 14. Compile BoxEncapsulatedWithHeader.cpp into another object file g++ -c BoxEncapsulatedWithHeader.cpp -o BoxEncapsulatedWithHeader.o Link both object files into an executable g++ BoxEncapsulatedWithHeader.o Box.o -o BoxEncapsulatedWithHeader Execute: ​BoxEncapsulatedWithHeader OUTPUT: ERROR: length cannot be greater than 5 toy dimensions: 5 4 3 tools dimensions: 4 7 6 Listing 7: BoxApp2.cpp #include <iostream> #include "Box.h" int main() { Box present; present.setLength(10); present.setLength(9); present.setLength(8); present.setLength(2); present.setWidth(20); present.setHeight(30); std::cout << "present dimensions: " << present.getLength() << " " << present.getWidth() << " " << present.getHeight() << std::endl; return 0; } Building the executable: (no need to re-compile Box.cpp) Compile BoxApp2.cpp into another object file g++ -c BoxApp2.cpp -o BoxApp2.o Link both object files into an executable g++ BoxApp2.o Box.o -o BoxApp2
  • 15. Execute: BoxApp2 OUTPUT: ERROR: length cannot be greater than 5 ERROR: length cannot be greater than 5 ERROR: length cannot be greater than 5 present dimensions: 2 20 30 - Our implementation of the Box class now supports multiple main programs without any duplication of code LAB3​: Write a class called Car with data for miles per gallon, make, and model. Use char arrays for make and model. Make data private and provide setters and getters. Place Car class declaration in file Car.h . Place Car class implementation in file Car.cpp . Create a driver program called CarDriver.cpp. Compile and link using g++ . Section 8: Adding Other Methods to your Class - classes can contain methods in addition to getters and setters - methods which clients need to call must be public - methods used internally should be private Listing 8: Box.h class Box { int length; int width; int height; ​bool lengthInRange(); ​ // private methods ​void printLengthError(); ​ // called only inside Box’s setLength() method public: int getLength(); int getWidth(); int getHeight(); void setLength(int len); void setWidth(int w); void setHeight(int h);
  • 16. ​ int computeVolume(); ​ // public method: client’s can call to compute Box’s volume }; Listing 9: From Box.cpp int Box::computeVolume() { return length * width * height; } Bool Box::lengthInRange(int len) { return len <= 5; } void Box::printLengthError() { std::cout << "ERROR: length cannot be greater than 5" << std::endl; } void Box::setLength(int len) { if ( ​lengthInRange(len)​ ) { length = len; } else { ​printLengthError(); } } Listing 10 : BoxApp3.cpp #include <iostream> #include "Box.h" int main()
  • 17. { Box present; present.setLength(10); present.setLength(2); present.setWidth(20); present.setHeight(30); std::cout << "present dimensions: " << present.getLength() << " " << present.getWidth() << " " << present.getHeight() << std::endl; int volume = present.computeVolume(); std::cout << “present volume = “ << volume << std::endl; return 0; } OUTPUT: ERROR: length cannot be greater than 5 ERROR: length cannot be greater than 5 ERROR: length cannot be greater than 5 present dimensions: 2 20 30 volume = 1200 LAB4​: Add an occupancy() method to the House class from LABs 1 and 2 which Returns the quotient of the number of rooms and the number of occupants. Write a HouseDriver program and call House’s occupancy() method from it. Copyright 2016 YourVirtualClass.com. All rights reserved.