OOP - Lab7 - Classes and Objects
OOP - Lab7 - Classes and Objects
PROGRAMMING
Lab Manual
Computer Science Spring 2023
CS Spring 2023
Lab#07
Classes and Objects
Everything in C++ is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color, and
methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These are
often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":
Example explained
The class keyword is used to create a class called MyClass.
The public keyword is an access specifier, which specifies that members (attributes and methods)
of the class are accessible from outside the class. You will learn more about access specifiers
later.
Inside the class, there is an integer variable myNum and a string variable myString. When
variables are declared within a class, they are called attributes.
At last, end the class definition with a semicolon ;.
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass, so
now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Example
Create an object called "myObj" and access the attributes:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
( Invoice Class) Create a class called Invoice that a hardware store might use to represent an invoice for
an item sold at the store. An Invoice should include four data members
1. a part number (type string ),
2. a part description (type string ),
3. a quantity of the item being purchased (type int ) and
4. a price per item (type int ).
Your class should have a constructor that initializes the four data members. Provide a set and a get
function for each data member. In addition, provide a member function named getInvoiceAmount that
calculates the invoice amount (i.e., multiplies the quantity by the price per item), then returns the amount
as an int value.
Submission Instructions
Save .cpp file with your Roll No, Lab No and Task Number e.g.
2202001001_Lab6_Problem01.cpp
Submit files on MS teams