03CSE225CPlusPlus Part01

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 35

Lecture 03

C++ Primer
CSE225: Data Structures and Algorithms
The Hello Program
#include <iostream>
using namespace std;

int main()
{
char name[100];
cout << "Enter your name: ";
cin >> name;
cout << "Hello “ << name << endl;
return 0;
}
C++ has two types of data types:

1. Primitive Data Type:


- Basic Unit of Language
- Each Primitive value is a single datum
Example: int , char, float, etc.

• 2. Composite Data Type:


- Multiple pieces of related data as a single datum
Example: array, structure, class, etc.

** What are the differences between Primitive and Composite


Data Types??
Array

• Stores a fixed-size sequential collection of elements of the


same type.
• All arrays consist of contiguous memory locations. The
lowest address corresponds to the first element and the
highest address to the last element.
• Declaration:
DataType ArrayName[dimension] = { element1, element2, …, elementn};

• One-dimensional Array
• Two –dimensional Array
Structure
- A linear, direct access data structure with
heterogeneous components
- A component is also called a field or a member
- Each field has its own type
- An identifier is used to name a field/component

Example:

struct CarType {
int year;
char maker[10];
Float price;
};
CarType MyCar;
Class and Object
• Class is a data type that encapsulates a fixed number of
data components with the functions that can access and/or
manipulate them
• It gives the C++ its identity from C
• It makes possible encapsulation, data hiding and inheritance
• Consists of both data and methods
• Defines properties and behavior of a set of entities
• Abstract concept: liken to the specification of a laptop
• Object
• An instance of a class
• A variable identified by a unique name
• Concrete concept: liken to an actual laptop having a given
specification
Objects
Object:
a variable or an instance of a class

OBJECT
set of methods
Operations (public member functions)

Data
internal state
(values of private data members)
Motivation for classes
• Object-Oriented Programming (OOP)
• Package together a set of related data and operations
(encapsulation)
• Allows programmer to define a class (abstract data type)
• One instance (variable) of a class is called an object
• The data and operations of a class are called its
members.
A Class & Its Objects

class Rectangle Rectangle r1;


{ Rectangle r2;
Rectangle r3;
private:
int width;
int length;
public:
void set(int w, int l);
int area();
}
Define a Class Type

class Rectangle
class class_name {
{ private:
permission_label: int width;
member;
int length;
permission_label:
member; public:
... void set(int w, int l);
}; int area();
};
Another Example//Circle.cpp file
//Circle.h file // member function definitions
#include <iostream.h>
void circle::store(double r)
class circle {
{ radius = r;
private: }
double radius; double circle::area(void)
{
public: return 3.14*radius*radius;
circle(); }
void store(double);
double area(void);
void circle::display(void)
{
void display(void); cout << “r = “ << radius << endl;
}
};
//main.cpp file
int main(void) {
circle c; // an object of circle class
c.store(5.0); cout << "The area of circle c is " << c.area() << endl;
c.display();
}
Class Definition - Access Control
• Information hiding
• To prevent the internal representation from direct access from outside the
class
• Access Specifiers
• public
• may be accessible from anywhere within a program
• private
• may be accessed only by the member functions, and friends of this
class, not open for nonmember functions
• Protected
• private members of derived/child classes
• Difference between classes and structs in C++
the default access specifier is private in class
the default access specifier is public in struct
Class Definition – Member Functions
• Used to
• access the values of the data members (accessor)
• perform operations on the data members (implementor)
• Are declared inside the class body, in the same way as
declaring a function
• Their definition can be placed inside the class body, or
outside the class body
• Can access both public and private members of the class
• Can be called using dot (for an object) or arrow (for a
pointer to an object) member access operator
Define a Member Function
class Rectangle
{
private:
int width, length; class name
public:
void set (int w, int l);
inline int area() {return width*length; } member function name

inline
void Rectangle :: set (int w, int l)
Rectangle r1;
{
r1.set(5,8); width = w;
length = l;
Rectangle *rp; scope operator
}
rp->set(8,10);
Defining Methods Separately
• For methods/functions that are declared but not defined in
the class we need to provide a separate definition
• To define the method, you define it as any other function,
except that the name of the function is written as:-

ClassName::FuncName
:: is the scope resolution operator, it allows us to refer to parts of a
class or structure
Inline Functions
• In an inline function, the C++ compiler does not make a
function call, instead the code of the function is inserted
(in .exe file) in place of the function call (and appropriate
argument substitutions are made)
• Why?
• It saves the memory space when a function is likely to be called
many times (no stack push happens)
• When we need to make the function call very fast.
• E.g. for accessing/changing fields of a class
• Compiler replaces the definition of inline functions at compile
time instead of referring function definition at runtime. 
Three Types of Functions
• Class member functions are classified into three
categories:
• Constructors
• create objects (allocate memory, set initial state)
• Modifiers
• change the state of objects
• Accessors
• make information about the state of the object available outside the class
Constructor
• Goal:
• construct objects of the class
• allocate memory
• Constructors MUST have the same name as the class itself.
• They don't have a return type. It's simply omitted.

• That's how you'll make instances of the class (objects).


• Example:
• Constructor of dateType class
• dateType();
• Constructor of rectangle class
• rectangle();
Constructor (Cont.)
• Constructors can be overloaded
Can have several constructors
• same name
• different lists of parameters
• This ability allows you to create
• a default constructor
• no parameters
• initializer constructors
• parameters specifying initial state of an object
Constructor Example
class Rectangle
{
private:
int width, length;
public:
//default constructor
Rectangle(){width=length=0;}
//another constructor
Rectangle(int w, int l){width=w; length=l;}
}
Modifiers
• The functions that do most of the work.
Note: Objects have three characteristics:
• name
• state
• set of operations
• Modifiers define the set of operations
Modifiers (Cont.)
• Allow the client to make changes to the private variables.
• Declarations look like the ones for nonmember functions.
• Often, but not always, they have a void return type.

• “Set” functions
• Modifiers that just "set" the value of a private variable from a
parameter without doing any calculations
Accessors
• Allow the client to see what values the private variables
have.
• Don't allow the client to make changes.
• Return type is that of the variable being "accessed."

• "Get" functions
• Accessors that just "get" the value of a private variable without
doing any calculations
More complicated accessors
• Some calculation based on the data
• as long as it doesn’t change the member data
• e.g. balance after interest w/o actually crediting it
• A data member converted to different units
• e.g. Fahrenheit version of Celsius temp.
• Part of a data member
• e.g. the cents part of a dollar amount
Pre- and Postconditions
• Preconditions
• What must be true for the method to behave as intended
• Anything about the state of the object?
• Should another method have been called first?
• May need to look at private data members individually
• Postconditions
• What is the state of the object after this method has been called?
What is returned or displayed?
• What private data members have changed? How?

• These conditions can be ensured using assert function


C++ Assert Function
• If the parameter (a logical expression) of assert function is
evaluates to false, then a message is written to the standard
error device and abort is called, terminating the program
execution.
• If the parameter evaluates to true, the program continues, as
usual.
• The specifics of the message shown depend on the particular
library implementation, but it shall at least include:
the expression whose assertion failed, the name of the source
file, and the line number where it happened. A usual
expression format is:

Assertion failed: expression, file filename, line line number 


Basics
• For every data structure, we will create 3 files in our
Codeblocks project
• The declaration file (with .h extension)
• The definition file (with .cpp extension)
• The driver file (with .cpp extension)
Class in a Separate Header File for Reusability

• Header files
• Separate files in which class definitions are placed.
• Allow compiler to recognize the classes when used elsewhere.
• Generally have .h filename extensions

• .cpp files for source-code implementations


• Class implementations
• Main programs
• Test programs

• Driver file
• A program used to test software (such as classes).
• Contains a main function so it can be executed
Basics
#ifndef DYNARR_H_INCLUDED
#define DYNARR_H_INCLUDED

class dynArr
{
private:
int *data;
int size;

public:
dynArr();
dynArr(int);
~dynArr();
void allocate(int);
void setValue(int, int);
int getValue(int);
};

#endif // DYNARR_H_INCLUDED
dynarr.h (header file)
Basics
#include "dynarr.h" void dynArr::allocate(int s)
#include <iostream> {
using namespace std; data = new int[s];
size = s;
dynArr::dynArr() }
{
data = NULL; int dynArr::getValue(int index)
size = 0; {
} return data[index];
}
dynArr::dynArr(int s)
{ void dynArr::setValue(int index, int
data = new int[s]; value)
size = s; {
} data[index] = value;
}
dynArr::~dynArr()
{
delete [] data;
}
dynarr.cpp (definition file)
Basics
#include "dynarr.h"
#include <iostream>
using namespace std;

int main()
{
dynArr d(10);
int i;

for(i=0;i<10;i++)
d. setValue(i,3*i+1);
for(i=0;i<10;i++)
cout << d.getValue(i) << endl;
return 0;
}

main.cpp (driver file)


Template Class
• Now we have a neat class that gives us a 1D dynamic array (you are
free to make your own improvisations at home by adding more
functions to the class)
• But it only works for integer type
• What if we are to make it versatile, so that it works for any type,
e.g. float, double and char
• Should we have separate classes for each type?
• Write the same code for each type with just minor changes?
• Instead, we can use template classes
Template Class
#ifndef DYNARR_H_INCLUDED
#define DYNARR_H_INCLUDED

template <class T>


class dynArr
{
private:
T *data;
int size;

public:
dynArr();
dynArr(int);
~dynArr();
void allocate(int);
void setValue(int, T);
T getValue(int);
};

#endif // DYNARR_H_INCLUDED
dynarr.h (declaration file)
Template Class
#include "dynarr.h" template <class T>
#include <iostream> void dynArr::allocate(int s)
using namespace std; {
data = new T[s];
template <class T> size = s;
dynArr<T>::dynArr() }
{
data = NULL;
size = 0; template <class T>
} T dynArr<T>::getValue(int index)
{
template <class T> return data[index];
dynArr<T>::dynArr(int s) }
{
data = new T[s];
template <class T>
size = s;
}
void dynArr<T>::setValue(int index, T
value)
template <class T> {
dynArr<T>::~dynArr() data[index] = value;
{ }
delete [] data;
} dynarr.cpp (definition file)
Template Class
#include "dynarr.h"
#include "dynarr.cpp"
#include <iostream>
using namespace std;

int main()
{
dynArr<int> di(10);
dynArr<double> dd(10);
int i;

for(i=0;i<10;i++)
{
di.setValue(i,3*i+1);
dd.setValue(i,7.29*i/1.45);
}
for(i=0;i<10;i++)
cout << di.get(i) << " " << dd.getValue(i) <<
endl;

return 0; main.cpp (driver file)

You might also like