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

Programming - U3 ( Custom Data Type )

Chapter 3 discusses custom data types in C++, including enumerations, structures, and classes. It explains how to define and use enumerated types, structures for grouping related variables, and introduces the concept of classes as templates for creating objects. The chapter also covers access specifiers, constructors, and member functions within classes.

Uploaded by

ermikasa2716
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Programming - U3 ( Custom Data Type )

Chapter 3 discusses custom data types in C++, including enumerations, structures, and classes. It explains how to define and use enumerated types, structures for grouping related variables, and introduces the concept of classes as templates for creating objects. The chapter also covers access specifiers, constructors, and member functions within classes.

Uploaded by

ermikasa2716
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Chapter 3

Custom Data Types


Custom Data Types

So far, we have been using data types built
into the C++ language (like int, double, …)

C++ allows us to define our own data types

In this lecture, we will see three constructs
that can be used to define our own data types

Enumerations

Structures

Classes
Enumerated Data Types

An enumerated data type is a programmer
defined data type that contains a set of
named integer constants.

For an enumerated data type, the legal set of
values that its variables can have are
enumerated, or listed, as part of the
definition of the data type.

These permissible values are called
enumerators.
Mood as an Enumerated Type

Example:

enum Mood {Depressed, Sad,


Happy,Ecstatic};


The declaration shown above creates a data type
named Mood.

A variable of type Mood may only have values
that are in the list inside the braces.
Defining and Using Variables
enum Mood {Depressed, Sad, Happy, Ecstatic};

Note that the above statement only defines the data
type and it does not create any variables.

A variable of the mood type can be defined like a
variable of any other type.
Mood today;

An assignment would look like
today = Happy;

A logical comparison would look like
if (today == Sad)
Example:
int main()
{
// Defining enum Gender
enum Gender { Male, Female };
// Creating Gender type variable
Gender gender = Male;
switch (gender)
{
case Male:
cout << "Gender is Male";
break;
case Female:
cout << "Gender is Female";
break;
default:
cout << "Value can be Male or Female";
}
return 0;
}
More example
using namespace std;
//specify enum type
enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
int main()
{
days_of_week day1, day2; //define variables
//of type days_of_week
day1 = Mon; //give values to
day2 = Thu; //variables
int diff = day2 - day1; //can do integer arithmetic
cout << "Days between = " << diff << endl;
if(day1 < day2) //can do comparisons
cout << "day1 comes before day2\n"<<day1;
return 0;
}

Write down the out put


Structures

So far we have seen that

A variable stores a single value of one type

An array stores multiple values of the same type

C++ allows us to group a set of variables of
(possibly different types) together into a
single item known as a structure.

These variables are related in same way –
they hold data about the same entity.
Example

For a student we may have the following data

Name (a string)

ID Number (a string)

Age (an integer)

Gender (an enumerated type)

Year (an integer)

Cumulative GPA (a floating point number)
The Student Data
• char name[30];
• char id[12];
• unsigned short age;
• Gender sex;
• unsigned short year;
• float cgpa;


These individual definitions do not make it clear
that these variables are related.
Creating a Relationship

Package these together into a structure
struct Student //keyword struct followed by a name
{
char name[30];
char id[12];
unsigned short age;
Gender sex;
unsigned short year;
float cgpa;
}; //notice the semicolon

The variables are now known as members of the structure.
Continued
• Now Student structure has been created with 6 attribute.
• When a structure is created, no memory is allocated.
• The structure definition is only the blueprint for the
creating of variables. You can imagine it as a datatype.
When you define an integer as below:
• int age;
• The int specifies that, variable age can hold integer
element only. Similarly, structure definition only specifies
that, what property a structure variable holds when it is
defined.
How to define a structure variable?

A variable of type Student can now be defined just like
any other variable
Student abe;
• When structure variable is defined, only then the
required memory is allocated by the compiler.
• Considering you have either 32-bit or 64-bit system,
the memory of float is 4 bytes, memory of int is 4
bytes and memory of char is 1 byte.
• How many byte of memory is allocated for structure
student?
How to access members of a structure?

• The members of structure variable is accessed


using a dot (.) operator.
• Suppose, you want to access age of structure
variable kebede and assign it 25 to it. You can
perform this task by using the following code
below:
• kebede.age = 50;
Example: C++ Structure
#include <iostream>
using namespace std;
struct Person { char name[50];
int age;
float salary; };
int main() { Person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl; cout << "Salary: " << p1.salary; return 0; }
Can and Can't Do

You can access and use the individual
members as you would use any other
variable.
cout<<abe.name<<abe.age;
if (abe.year > 1) ...

You can't perform operations on the entire
struct
cout<<abe; //error
if (abe == kebe) //error
Initializing a Structure

You can initialize the members of a structure
in two ways

Using an initializer list (like in arrays)

Using a constructor
Student abebe = {“Abebe”, “tcr/1234/01”, 19,
MALE, 2, 3.40};
Structure and Function
• Structure variables can be passed to a
function and returned in a similar way as
normal arguments.
Passing structure to function

• A structure variable can be passed to a


function in similar way as normal argument.
Consider this example:

#include <iostream>
int main() {
using namespace void displayData(Person p)
Person p;
std; struct Person { cout << "\nDisplaying
Int person
{ char name[50]; Information." << endl;
cout << "Enter Full name:
int age; cout << "Name: " <<
"; cin.get(p.name, 50);
float salary; }; p.name << endl;
cout << "Enter age: ";
void cout <<"Age: " << p.age <<
cin >> p.age;
displayData(Person); endl;
cout << "Enter salary: ";
cout << "Salary: " <<
cin >> p.salary;
p.salary; }
displayData(p);
return 0; }
Returning structure from function
#include <iostream>
using namespace std; Person getData(Person p)
struct Person { { cout << "Enter Full name: ";
char name[50]; cin.get(p.name, 50);
int age; cout << "Enter age: ";
float salary; cin >> p.age;
}; cout << "Enter salary: ";
Person getData(Person); cin >> p.salary;
void displayData(Person); return p; }
void displayData(Person p)
int main() { {
Person p, temp; cout << "\nDisplaying Information." << endl;
temp = getData(p); cout << "Name: " << p.name << endl;
p = temp; cout <<"Age: " << p.age << endl;
displayData(p); cout << "Salary: " << p.salary;
return 0; }
}
5.6. Introduction to Classes
Abstraction

An abstraction is a general model of something.

It is a definition that includes only the general
characteristics of an object without going into all
the details that characterize specific instances of
the object.

For example, the term “car” is an abstraction. It
defines a general type of vehicle. The term captures
the essence of what all cars are without specifying
the detailed characteristics of any particular type of
car.
Abstraction Continued

While the term car is abstract, a particular, real life car (for
example, a blue Toyota Corolla DX 1983 model, …) is
concrete.

Real life cars come in many shapes, sizes, colors, and
capabilities.

Most people have an idea of a car and they know how to
drive one. But a few know about the internal workings of
the car.

You don't need to know the details of how a car works just
to drive it.

Can you find out other real-world abstractions?
Abstract Data Type

An abstract data type (ADT) is a data type that specifies
the values the data type can hold and the operations that
can be done on them without the need for anyone using
the ADT to know how the data type itself is implemented.

Commonly, ADT refers to programmer defined types.

The programmer defines a set of values the data type can
hold, defines a set of operations that can be performed on
the data, and creates a set of functions to carry out these
operations.

In C++, ADTs are mainly implemented as classes
Classes and Objects

A class is similar to a structure.

In addition to what we have seen for a
structure, a class can also contain functions.
(Note: in C++, a structure can also contain
functions but it is rarely used that way)

Objects are instances of a class. They are
created with a definition statement after a
class has been declared.
Declaring Classes
• class Student {
• private: //an access specifier
• char name[30];
• public: //another access specifier
• int age;
• void setName(char [] nm) {
• strcpy(name, nm);
• } //the first function ends here
• int getAgePlus(int plus) {
• return age + plus;
• } //the last function ends here
• }; //the class definition ends here. Notice the
semicolon
Access Specifiers

The terms private and public in the previous
class declaration are known as access specifiers.

The access specifiers designate who can access
the various members of the class.

Public: can be accessed/called by functions outside
the class

Private: can only be accessed/called by functions
inside the class.

Protected: Not to be discussed at this point.
Defining and Using Objects
• Student me; //the object me is
created
• char myName[] = “Biruk”;
• me.setName(myName); //setName is
public
• me.age = 14; //age is public
• cout<<me.getAgePlus(4);

• strcat(me.name, “ Wendimagegn”);
• //error because name is private.
More about Objects and Classes

A class is a template for an object.

A class is like a blueprint (a plan) from which
objects are created.

No memory is occupied when a class is
defined.

The objects reside in memory.
Member Functions

Class member functions can be defined either
inside or outside of a class declaration.

When a member function is define inside a
class declaration, it is known as inline
function.
Constructor

A constructor is a member function that gets
executed automatically when an object is
created.

It is used to initialize member variables.

Constructors have the following
characteristics

They don't have a return type

They have the same name as the class

They are found under the public access specifier
Example
• class Student {
• char name[30]; char myName[] =
• int age; “Biruk”;
• public:
• Student(char [] nm, int
Student me(myName,
a) 14);
• {
• strcpy(name, nm);
• age = a; //can I do this?
• }
cout<<me.name;
• //other member
functions
• };
More about Constructors

A constructor that accepts no arguments is
called a Default Constructor.

A constructor is just like any other function.
i.e. It can do more than just initialization.

The initialization can be done alternatively by
using a member initializer list.
1 class Time {
2 public:
Public: and Private: are
3 Time();
member-access specifiers.
4 void setTime( int, int, int );
5 void printMilitary(); setTime, printMilitary, and
6 void printStandard(); printStandard are member
7 private: functions.
Time is the constructor.
8 int hour; // 0 - 23
9 int minute; // 0 - 59
10 int second; // 0 - 59 hour, minute, and
11 }; second are data members.
1 // Fig. 6.3: fig06_03.cpp
2 // Time class.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // Time abstract data type (ADT) definition
9 class Time {
10 public:
11 Time(); // constructor
12 void setTime( int, int, int ); // set hour, minute, second
13 void printMilitary(); // print military time format
14 void printStandard(); // print standard time format
15 private:
16 int hour; // 0 – 23
17 int minute; // 0 – 59
18 int second; // 0 – 59
19 };
20
21 // Time constructor initializes each data member to zero.
22 // Ensures all Time objects start in a consistent state. Note the :: preceding
23 Time::Time() { hour = minute = second = 0; } the function names.
24
25 // Set a new Time value using military time. Perform validity
26 // checks on the data values. Set invalid values to zero.
27 void Time::setTime( int h, int m, int s )
28 {
29 hour = ( h >= 0 && h < 24 ) ? h : 0;
30 minute = ( m >= 0 && m < 60 ) ? m : 0;
31 second = ( s >= 0 && s < 60 ) ? s : 0;
32 }
33
34 // Print Time in military format
35 void Time::printMilitary()
36 {
37 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
38 << ( minute < 10 ? "0" : "" ) << minute;
39 }
40
41 // Print Time in standard format
42 void Time::printStandard()
43 {
44 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
45 << ":" << ( minute < 10 ? "0" : "" ) << minute
46 << ":" << ( second < 10 ? "0" : "" ) << second
47 << ( hour < 12 ? " AM" : " PM" );
48 }
49
50 // Driver to test simple class Time
51 int main()
52 {
53 Time t; // instantiate object t of class Time
54
55 cout << "The initial military time is ";
56 t.printMilitary();
57 cout << "\nThe initial standard time is ";
58 t.printStandard();
59
60 t.setTime( 13, 27, 6 );
61 cout << "\n\nMilitary time after setTime is ";
62 t.printMilitary();
63 cout << "\nStandard time after setTime is ";
64 t.printStandard();
65
66 t.setTime( 99, 99, 99 ); // attempt invalid settings
67 cout << "\n\nAfter attempting invalid settings:"
68 << "\nMilitary time: ";
69 t.printMilitary();
70 cout << "\nStandard time: ";
71 t.printStandard();
72 cout << endl;
73 return 0;
74 }

The initial military time is 00:00


The initial standard time is 12:00:00 AM

Military time after setTime is 13:27


Standard time after setTime is 1:27:06 PM

After attempting invalid settings:


Military time: 00:00
Standard time: 12:00:00 AM
Thank you.

You might also like