6. Structures and Classes (1)
6. Structures and Classes (1)
1. Primitive
2. Derived data type
3. User-defined data type
• Structures
• Classes
2
Structures
• A very rudimentary comparison:
• int num = 10;
Data type Identifier Value Stores only one
int num 10 type of data
SYNTAX:
struct FixedDeposit {
int accnr;
float amt;
float rate;
int months;
};
3
Structure in C++
• Structures are usually written outside all functions
SYNTAX:
• Keyword struct announces that this is a structure-type definition struct FixedDeposit {
int accnr;
• structure tags are usually spelled with a mix of uppercase and float amt;
lowercase letters, beginning with an uppercase letter. float rate;
int months;
• The identifiers declared inside the braces, { }, are called member };
names; it ends with a semicolon (;).
• The structure type is then available to all the code that follows the
structure definition.
4
Structure in C++: As function arguments
#include <iostream>
void feeddata(FixedDeposit &fd){
#include <cstdlib>
cout << "Enter principal ";
using namespace std;
cin >> fd.amt;
cout << "Enter period in months ";
struct FixedDeposit {
cin >> fd.months;
int accnr;
cout << "Enter yearly interest rate ";
float amt;
cin >> fd.rate;
float rate;
}
int months;
};
void calculateInterest (FixedDeposit &fd){
fd.amt += fd.amt*(fd.months/12)*(fd.rate/100);
int main(){
}
FixedDeposit fd;
feeddata (fd); Can you guess the function
calculateInterest (fd); argument type?
5
Structure in C++: As arrays
FixedDeposit feeddata();
void calculateInterest (FixedDeposit &fd);
6
Structure in C++: Direct initialization
#include <iostream>
using namespace std;
Fewer members: each data member
struct FixedDeposit { without an initializer is initialized to a
int accnr; zero value of an appropriate type for
float amt; the variable.
float rate;
int months;
};
void calculateInterest (FixedDeposit &fd){
fd.amt += fd.amt*(fd.months/12)*(fd.rate/100);
}
int main(){ Order is important
FixedDeposit fd = {1000, 12, 10};
calculateInterest (fd);
cout << "The maturity Amount is: " << fd.amt;
return 0;
}
7
Structure in C++
struct date {
int date;
int month;
int year;
};
struct FixedDeposit {
int accnr;
float amt;
float rate;
int months;
date dob;
};
8
Scope
• As programs get larger and more complicated, the number of identifiers in a
program increases.
• Some of these identifiers we declare inside blocks
• Other identifiers—function names, for example—we declare outside of
any block
9
Scope
10
Classes, Objects in C++
• C++ is an object-oriented programming language.
• C++ has classes and objects which, in turn, have attributes and
methods.
• Example: bicycle
• Attributes: break, seat, handle, weight, type
• Functions (or methods): to ride, to break
• Attributes are variables
• Together, they are called as class members.
11
Classes, Objects in C++
Abstraction
Instantiation
12
Classes, Objects in C++
13
Classes, Objects in C++
14
Object
• Object: a self-contained entity encapsulating data and operations on the data.
• An object has an internal state (the current values of its data called attributes),
and it has a set of methods (operations, which are implemented by functions
in C++).
15
Classes, Objects in C++
class MyClass{
public:
int myNum; Creating single instance
string myString;
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString << endl;
return 0;
Can we have structure
} inside a class?
16
Classes, Objects in C++
class Car{ //Class name
public: //Access specifier
string brand; //Attribute1 Creating multiple
string model; //Attribute2
instance
int year; //Attribute3
};
int main(){
// Create Car objects
Car car1;
car1. brand = "Tata";
car1.model = "Nexon";
car1.year = 2023;
Car car2;
car2. brand = "Maruti";
car2.model = "Brezza";
car2.year = 2015;
//Print values
cout << car1.brand << " " << car1.model << " " << car1.year << endl;
cout << car2.brand << " " << car2.model << " " << car2.year << endl;
return 0;
}
17
Classes, Objects in C++: Methods
• Class methods:
• Inside class definition
• Outside class definition (This is done by specifying the name
of the class, followed the scope resolution :: operator,
followed by the name of the function)
18
Classes, Objects in C++: Methods
• Class methods:
• Inside class definition
• Outside class definition (This is done by specifying the name
of the class, followed the scope resolution :: operator,
followed by the name of the function)
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
19
Classes, Objects in C++: Methods
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth; Declaring and defining
}
double calculateVolume() {
methods inside class
return length * breadth * height;
}
};
int main() {
Room room1; // create object of Room class
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Defining methods outside class
Syntax:
Return_type class_name::method_name(){
method_body
}
21
Classes, Objects in C++: Method parameters
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
22
Classes, Objects in C++: Constructor
To create a constructor, use the same name as the class, followed by parentheses ():
#include <iostream>
using namespace std;
class Myclass{
public:
Myclass(){ //Constructor defined
cout << "Hello World!!";
}
};
As soon as the object is created, the
int main(){
Myclass obj; associated constructor function is called
return 0;
}
23
Classes, Objects in C++: Constructor parameters
class Car { // The class
public: // Access specifier
string brand; // Attribute Note that constructor has:
string model; // Attribute
int year; // Attribute
1. Same name as the class
//Constructor definition inside the class 2. No return type
Car(string x, string y, int z){
brand = x;
model = y; A constructor is used to initialize the
year = z; values of member variables
};
24
Classes, Objects in C++: Constructor parameters
class Car{ //Class name
public: //Access specifier
string brand; //Attribute1
string model; //Attribute2
int year; //Attribute3
Car(string x, string y, int z){ //Constructor with parameters
brand = x;
model = y;
year = z; A constructor is used to initialize the
} values of member variables
};
int main(){
// Create Car objects and call the constructor with different values
Car car1("Tata", "Nexon", 2023);
Car car2("Maruti", "Brezza", 2015);
//Print values
cout << car1.brand << " " << car1.model << " " << car1.year << endl;
cout << car2.brand << " " << car2.model << " " << car2.year << endl;
return 0;
}
25
Classes, Objects in C++: Constructor calling
#include <iostream>
using namespace std; A constructor can be called:
class BankAcc{ 1. Implicitly when an object is created
public:
int amt;
2. Explicitly to create an object
int rate;
int duration;
BankAcc(int a, int b, int c){ //Constructor defined
amt = a; rate = b; duration = c;
}
};
int main(){
BankAcc a1(100,2,10); //Implicit calling
BankAcc a2 = BankAcc(200, 4, 12); //Explicit calling
cout << a1.amt << " " << a1.rate << " "<< a1.duration << endl;
cout << a2.amt << " " << a2.rate << " "<< a2.duration << endl;
return 0;
}
26
Classes, Objects in C++: Constructor overloading
#include <iostream>
using namespace std;
class BankAcc{
public:
Can constructors be overloaded?
int amt;
int rate;
int duration;
BankAcc(int a, int b, int c){ // Overloading 1
amt = a; rate = b; duration = c;
}
BankAcc(int a, int b){ // Overloading 2
amt = a; rate = b; duration = 0;
}
BankAcc(){ // Overloading 3
amt = 0; rate = 0; duration = 0;
}
};
int main(){
BankAcc a1(100,2,10), a2(200, 4), a3;
cout << a1.amt << " " << a1.rate << " "<< a1.duration << endl;
cout << a2.amt << " " << a2.rate << " "<< a2.duration << endl;
cout << a3.amt << " " << a3.rate << " "<< a3.duration << endl;
return 0;
}
27
Classes, Objects in C++: Access Specifiers
• public: A public member of a class is accessible anywhere
• protected: A protected member of a class is only accessible (a) to the members and (b) to
the members of any derived class of that class
• private: A private member of a class is only accessible to the members
• If we do not specify any access modifiers for the members inside the class, then by default,
the access modifier for the members will be private.
• If we do not specify any access modifiers for the members inside the struct, then by
default, the access modifier for the members will be public.
28
Classes, Objects in C++: Access Specifiers
• When defining a class, the normal practice is to make all member variables private.
• This means that the member variables can only be accessed or changed using the
member functions.
29
Classes, Objects in C++: Access Specifiers
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
30
Classes, Objects in C++: Access Specifiers
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
31