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

Lecture 4

Structures in C and C++ have some key differences: - In C, all structure members are public by default, while in C++ they are private by default. - C structures cannot contain member functions or have constructors, while C++ structures can. - C requires the use of the struct keyword to declare structure variables, but C++ does not require this. - C structures cannot have static members or data hiding capabilities, while C++ structures allow these features.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Lecture 4

Structures in C and C++ have some key differences: - In C, all structure members are public by default, while in C++ they are private by default. - C structures cannot contain member functions or have constructors, while C++ structures can. - C requires the use of the struct keyword to declare structure variables, but C++ does not require this. - C structures cannot have static members or data hiding capabilities, while C++ structures allow these features.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 56

Lecture 4-5

CSE202: OBJECT ORIENTED PROGRAMMING


Outline

 Structures, Unions
 Enumeration
 Inline and Non-inline member functions
Why Use Structures?

• Quite often we deal with entities that are collection of


dissimilar data types.
• For example, suppose you want to store data about a
car. You might want to store its name (a string), its
price (a float) and number of seats in it (an int).
• If data about say 3 such cars is to be stored, then we can
follow two approaches:
– Construct individual arrays, one for storing names, another for
storing prices and still another for storing number of seats.
– Use a structure variable.
Introduction

• Structures are derived data types


• Structures
– Structure is a group of data items of different data types
held together in a single unit.
– Collections of related variables under one name
• Can contain variables of different data types
– Commonly used to define records to be stored in files.
Structure

• There are three aspects of working with structures:


– Defining a structure type
– Declaring variables and constants of newly created type
– Using and performing operations on the objects of
structure type
Structure Definition

struct sname {
type var1;
type var2;
type var3;
.
.
type varN;
};

struct is a keyword to define a structure.


sname is the name given to the structure/structure
tag.
type is a built-in data type.
var1,var2,var3,…..,varN are elements of structure
being defined.
; semicolon at the end.
Structure Definitions
• Example:
struct car{
char n[20];
int seats;
float price
};
– struct keyword introduces the definition for structure car
– car is the structure name or tag and is used to declare variables of the
structure type
– car contains three members of type char, float, int
• These members are name, price and seats.
 No variable has been associated with this structure
 No memory is set aside for this structure.
Structure Definitions
• struct information
– A structure definition does not reserve space in memory .
• Instead creates a new data type used to define structure variables
• Defining variables of structure type
– Defined like other variables:
Car myCar1,mycar2…
– Can use a comma separated list along with structure definition:
struct car{
char n[20];
int seats;
float price;
} myCar;

At this point, the memory is set aside for the structure variable
myCar.
Structure is a data type in which
A elements must have same data types
B elements may have different data types
C elements must have different data types
D none of these
Structure is a data type in which
A elements must have same data types
B elements may have different data types
C elements must have different data types
D none of these
A structure is a collection of
A homogenous e elements
B heterogenous elements
C homogenous elements and heterogenous elements
A structure is a collection of
A homogenous e elements
B heterogenous elements
C homogenous elements and heterogenous elements
How the members are stored
in memory
Consider the declarations to understand how the members of
the structure variables are stored in memory
struct car{
int seats;
float price;
}myCar,

Note: all members are stored in contiguous memory location in order in which they are
declared.
How the members of the structure variables are stored in memory

1197
1198
1199

seats 1200
1201
1202
1203
1204
price
1205
1206
1207
1208
1209
1210
1211
Program example
#include <iostream>
using namespace std;
struct employee
{
char name[50];
int age;
float salary;
};

int main()
{
employee e1;
cout << "Enter Full name: ";
cin.get(e1.name, 50);
cout << "Enter age: ";
cin >> e1.age;
cout << "Enter salary: ";
cin >> e1.salary;
cout << "\nDisplaying Information." << endl;
cout << "Name: " << e1.name << endl;
cout <<"Age: " << e1.age << endl;
cout << "Salary: " << e1.salary;
return 0;
}
Union
• Union is similar as structure. The major
distinction between them is in terms of
storage.
• In structure each member has its own storage
location whereas all the members of union
uses the same location.
• The union may contain many members of
different data type but it can handle only one
member at a time union can be declared using
the keyword union.
©LPU CSE101 C Programming
Example
• A class is a very good example of structure and union in this
example students are sitting in contiguous memory
allocation as they are treated as a structure individually. And
if we are taking the place of teacher then in a class only one
teacher can teach. After leaving the first teacher then another
teacher can enter.

©LPU CSE101 C Programming


Union Declaration
union item
{
int m;
float x;
char c;
}code;

This declare a variable code of type union item

©LPU CSE101 C Programming


Unions
• Valid union operations
– Assignment to union of same type: =
– Taking address: &
– Accessing union members: .
– Accessing members using pointers: ->

©LPU CSE101 C Programming


Which statement is true in case of memory allocation of
members of union
A Memory is allocated for all variables.
B Allocates memory for variable which variable require
more memory.
C Allocates memory for variable which variable require
less memory.
D none of these

©LPU CSE101 C Programming


Which statement is true in case of memory allocation of
members of union
A Memory is allocated for all variables.
B Allocates memory for variable which variable
require more memory.
C Allocates memory for variable which variable require
less memory.
D none of these

©LPU CSE101 C Programming


which is true in case of union
A require more memory space than Structure
B Declared with Struct Keyword
C require less memory space than Structure
D require more execution time than Structure

©LPU CSE101 C Programming


which is true in case of union
A require more memory space than Structure
B Declared with Struct Keyword
C require less memory space than Structure
D require more execution time than Structure

©LPU CSE101 C Programming


C structure differs from CPP class in regards that by
default all the members of the structure are __________
in nature.

a. private
b. protected
c. public
d. None of these
C structure differs from CPP class in regards that by
default all the members of the structure are __________
in nature.

a. private
b. protected
c. public
d. None of these
Difference between C structures and C++ structures
 Member functions inside structure: Structures in C cannot
have member functions inside structure but Structures in C++
can have member functions along with data members.
 Direct Initialization: We cannot directly initialize structure
data members in C but we can do it in C++.

#include <iostream>
using namespace std;
struct Record {
int x = 7;
};
int main()
{
Record s;
cout << s.x << endl;
return 0;
}
 Using struct keyword: In C, we need to use struct to declare a
struct variable. In C++, struct is not necessary. For example, let
there be a structure for Record. In C, we must use “struct
Record” for Record variables. In C++, we need not use struct
and using ‘Record‘ only would work.
 Static Members: C structures cannot have static members but
is allowed in C++.

struct Record {
static int x;
};
int main()
{
return 0;
}

Note: This will generate an error in C but no error in C++.


 Constructor creation in structure: Structures in C cannot
have constructor inside structure but Structures in C++ can
have Constructor creation.
 sizeof operator: This operator will generate 0 for an empty
structure in C whereas 1 for an empty structure in C++.
 Data Hiding: C structures do not allow concept of Data hiding
but is permitted in C++ as C++ is an object oriented language
whereas C is not.
 Access Modifiers: C structures do not have access modifiers as
these modifiers are not supported by the language. C++
structures can have this concept as it is inbuilt in the language.
Enumeration (ENUM)
An enumeration is a user-defined type consisting of a set of named constants
called enumerators
 It is a user-defined data type which can be assigned some limited values.
These values are defined by the programmer at the time of declaring the
enumerated type.
 The values that we specify for the data type must be legal identifiers
 The syntax for declaring an enumeration type is:

enum typeName{value1, value2, ...};

The syntax to declare an enum is as follows:


enum model_name
{
value1,
value2,
value3,
. .
};
Declaration of Enumerated Types
 Consider the colors of the rainbow as an enumerated type:

enum rainbowColors{ red, orange, yellow, green, blue, indigo,


violate };

 The identifiers between { } are called enumerators

 The order of the declaration is significant


red < orange < yellow

 By default, the first enumerator has a value of 0


 Each successive enumerator is one larger than the value of the previous
one, unless you explicitly specify a value for a particular enumerator
32
Declaration of Enumerated Types
• Why are the following illegal declarations?
enum grades{'A', 'B', 'C', 'D', 'F’};

enum places{1st, 2nd, 3rd, 4th};

They do not have legal identifiers in the list..

• What could you do to make them legal?


enum grades{A, B, C, D, F};
enum places{first, second, third, fourth};

33
• As with the declaration of any object
– Specify the type name
– Followed by the objects of that type

Given:
enum daysOfWeek { Sun, Mon, Tue,Wed, Thu, Fri, Sat }

Then we declare:
daysOfWeek Today, payDay, dayOff;

34
Assignment with Enumerated Types
 Once an enumerated variable has been declared
 It may be assigned an enumerated value
 Assignment statement works as expected

payDay = Fri; // note: no quotes


// Fri is a value, a constant

 Enumerated variables may receive only values of that


enumerated type

35
Example 1:
main()
{
enum days{sun,mon,tues,wed,thur,fri,sat};
days day1,day2;
day1=sun;
day2=fri;
cout<<day1<<“\t”<<day2;
if(day1>day2)
{
cout<<“day1 comes after day2”;
}
else
{
cout<<“day1 comes before day2”;
}
}
Example 2:

#include <iostream>
using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday,


Thursday, Friday, Saturday };

int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}
Example 3: Changing Default Value of Enums
#include <iostream>
using namespace std;

enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main() {

seasons s;

s = summer;
cout << "Summer = " << s << endl;

return 0;
}
Find the output of below program
#include<iostream>
using namespace std;
enum color{
Black,
blue,
red
};
int main()
(A) blue
{ (B) 2
color obj = blue; (C) 1
cout<<obj; (D) None of these
return 0;
}
Find the output of below program
#include<iostream>
using namespace std;
enum color{
Black,
blue,
red
};
int main()
(A) blue
{ (B) 2
color obj = blue; (C) 1
cout<<obj; (D) None of these
return 0;
}
Find Output:
#include<iostream>
using namespace std;
enum color{
black=1,
blue,
red
};
int main()
(A) blue
{
(B) Compilation Error
color obj = blue;
(C) 1
cout<<obj; (D) 2
return 0;
}
Find Output:
#include<iostream>
using namespace std;
enum color{
black=1,
blue,
red
};
int main()
(A) blue
{
(B) Compilation Error
color obj = blue;
(C) 1
cout<<obj; (D) 2
return 0;
}
Find Output:
#include<iostream>
using namespace std;
enum color{
black=1,
blue,
red
};
int main()
(A) yellow
{
(B) Compilation Error
color obj =yellow;
(C) 1
cout<<obj; (D) 2
return 0;
}
Find Output:
#include<iostream>
using namespace std;
enum color{
black=1,
blue,
red
};
int main()
(A) yellow
{
(B) Compilation Error
color obj =yellow; (C) 1
cout<<obj; (D) 2
return 0;
}
C++ inline function
• C++ inline function is powerful concept that is commonly used with
classes. If a function is inline, the compiler places a copy of the code of that
function at each point where the function is called at compile time.
• Every time a function is called, it takes a lot of extra time in executing a
series of instructions for tasks such as jumping to the function, saving
registers, pushing arguments into the stack, and returning to the calling
function.
• When a function is small, a substantial percentage of execution time may be
spent in such overheads.
• To eliminate the cost of calls to smaller functions, C++ introduces a new
feature called inline function, which is expanded in line when it is invoked.
#include <iostream>
using namespace std;
inline int Max(int x, int y) {
return (x > y)? x : y;
}
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
Inline Member Function
• To inline a function, place the keyword inline before the function
name and define the function before any calls are made to the
function. The compiler can ignore the inline qualifier in case defined
function is more than 3-5 lines.
• A function definition in a class definition is an inline function
definition, even without the use of the inline specifier.
A member function that is defined inside its class member list is called
an inline member function.
An equivalent way to declare an inline member function is to either
declare it in the class with the inline keyword (and define the
function outside of its class) or to define it outside of the class
declaration using the inline keyword.
#include <iostream>
using namespace std;
class operation
{ Method 1: Inline Member Function
int a,b,add;
public:
void get() // inline Member Function
{ int main()
cout << "Enter first value:"; {
cin >> a; cout << "Program using inline function\n";
cout << "Enter second value:"; s.get();
cin >> b; s.sum();
} return 0;
void sum(); }
}s;
inline void operation :: sum() Method 2: Inline Member Function
{
add = a+b;
cout <<"Addition of two numbers: " << a+b;
}
Note: Inlining is only a request to the compiler, not a command.
Compiler can ignore the request for inlining. Compiler may not
perform inlining in such circumstances like:

1) If a function contains a loop. (for, while, do-while)


2) If a function contains static variables.
3) If a function is recursive.
4) For Functions not returning values, if a return statement exists
5) If a function contains switch or goto statement.
Inline functions provide following advantages:

1) Function call overhead doesn’t occur.

2) It also saves overhead of a return call from a function.

Disadvantages:
It makes the program to take up more memory because the statements that define the
inline function are reproduced at each point where the function is called.

Inline function may increase compile time overhead if someone changes the code
inside the inline function then all the calling location has to be recompiled because
compiler would require to replace all the code once again to reflect the changes,
otherwise it will continue with old functionality.
When the function is defined inside a class, it is treated as
………………….

A) data function
B) inline function
C) non inline function
D) member variable
When the function is defined inside a class, it is treated as
………………….

A) data function
B) inline function
C) non inline function
D) member variable
Function which are declared in a class declaration and defined
outside the class is known as……………….

A) inline member function


B) non-inline member function
C) static member function
D) dynamic member function
Function which are declared in a class declaration and defined
outside the class is known as……………….

A) inline member function


B) non-inline member function
C) static member function
D) dynamic member function
True about inline function statements in C++
class A
{ public:
void func1()
{}
void func2();
};
inline void A::func2()
{}
1.Func1 is inline function
2.Func2 only is inline function
3.Func1 and Func2 both are inline functions
4.None of the above is inline
True about inline function statements in C++
class A
{ public:
void func1()
{}
void func2();
};
inline void A::func2()
{}
1.Func1 is inline function
2.Func2 only is inline function
3.Func1 and Func2 both are inline functions
4.None of the above is inline

You might also like