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

6. Structures and Classes (1)

The document provides an overview of computer programming concepts in C++, focusing on structures and classes. It covers topics such as data types, scope, object-oriented programming principles, and the use of constructors and access specifiers. The content includes syntax examples and explanations for defining and using structures and classes in C++.

Uploaded by

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

6. Structures and Classes (1)

The document provides an overview of computer programming concepts in C++, focusing on structures and classes. It covers topics such as data types, scope, object-oriented programming principles, and the use of constructors and access specifiers. The content includes syntax examples and explanations for defining and using structures and classes in C++.

Uploaded by

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

INDIAN INSTITUTE OF TECHNOLOGY ROORKEE

CEC-101: Computer Programming


Structures and Classes

Prof. Amit Agarwal; Prof. Anjaneya Dixit


A quick recap

• Programming basics in C++ (input/output)


• Data types, variables, operators
• Conditional and iterative statements
• Strings, Arrays
• Function (Syntax, parameters, calling, overloading)
• Reference, pointers and dynamic memory

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

Data type Identifier Value(s) Stores multiple


Structure FixedDeposit Account number, types of data
Amount,
Intertest Rate,
Months

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.

• The dot operator is used to specify a member variable of a


structure variable.
• FixedDeposit acc1; //Declaring a struct acc1 of type FixedDeposit
• acc1.months = 12; //Initializing the value of months for acc1 to 12

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?

cout << "The maturity Amount is: " << fd.amt;


return 0;
}

5
Structure in C++: As arrays

FixedDeposit feeddata();
void calculateInterest (FixedDeposit &fd);

int main(){ FixedDeposit feeddata(){


int num; FixedDeposit fd;
cout << "Enter number of FDs : " ; cout << "Enter principal ";
cin >> num; cin >> fd.amt;
cout << "Enter period in months ";
FixedDeposit fd [num]; cin >> fd.months;
for (int i=0; i<num; i++){ cout << "Enter yearly interest rate ";
fd[i]=feeddata(); cin >> fd.rate;
calculateInterest(fd[i]); return fd;
} }
for (int i=0; i<num; i++){
cout << "The maturity Amount is: " << fd[i].amt; void calculateInterest (FixedDeposit &fd){
} fd.amt += fd.amt*(fd.months/12)*(fd.rate/100);
return 0; }
}

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++

Can we have structure inside a structure?

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

• Scope: The region of program code where it is legal to reference (use) an


identifier.
• Local: The scope of an identifier declared inside a block extends from the
point of declaration to the end of that block. E.g., function, function
parameter has scope same as if a variable is declared in it
• Global: The scope of an identifier declared outside all functions and classes
extends from the point of declaration to the end of the entire file
containing the program code.
• Class: To say that a member name has class scope means that the name is
bound to that class.

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.

• Sometimes, it's desirable to put related functions and data in one


place so that it's logical and easier to work with.

• A class is a blueprint for the object. One can think of a class as a


sketch (prototype) of a house.

• It is a user-defined data type, which holds its own data


members and member functions, which can be accessed and used
by creating an instance of that class.

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++).

• An object-oriented program consists of a collection of objects, which


communicate with one another by message passing. If object A wants object B
to perform some task, object A sends a message containing the name of the
object (B, in this case) and the name of the particular method to execute.

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)

class MyClass { // The class


public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};

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

// 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;
}
20
Classes, Objects in C++: Methods
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};

// Method/function definition outside the class


void MyClass::myMethod() {
cout << "Hello World!";
}

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 Car::speed(int maxSpeed) {


return 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

A constructor in C++ is a special method that is automatically called when an object of a


class is created. It does not have a return type.

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
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
} Use of scope resolution operator, ::,
like the case of member functions

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

In C++, there are three access specifiers:

• public - members are accessible from outside the class


• private - members cannot be accessed (or viewed) from outside the class
• protected - members cannot be accessed from outside the class, however, they can be
accessed in inherited classes.
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

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

You might also like