Computer Programming in C+
Unit-II
Variable
Array and Strings
Classes member functions
Friend function
Inline function
Stored Data
•Variables (objects) must be declared as a certain type, e.g., int, float,
char, … This declaration may appear anywhere in the program, as long
as it appears before the variable is first used. The declaration creates
the object.
•For the following declaration,
•int n;
Names (Identifiers)
•Variables and other program elements will have to have names.
Names should be meaningful to help document your program.
– may use letters, digits, underscores. No spaces.
– may not begin with a digit
– may be any length but better if less than 31 characters long.
– C++ is case sensitive; upper and lower case letters are different.
– no reserved words (e.g., const, void, int, …).
– Avoid using names beginning with _ (underscore) or _ _ (double
underscore). The C++ compiler uses names like that for special
purposes.
Stream Input / Output
• cout << //means “cout gets a value”
• cin >> var //means “cin gives a value to var”
• //note: on execution press enter key to end input
• >> is the stream extraction operator
• << is the stream insertion operator
– The stream insertion operator “knows” how to output different
types of data.
•Cascading stream insertion operators - using multiple stream insertion
operators in a single statement. Also known as concatenating or
chaining, e.g.,
• cout << “The answer is: ” << result << ".\n";
About Data Types
• A data type is a template for
– how a particular set of values is represented in memory, and
– what operations can be performed on those values.
•
• In C++ a type is the same as a class.
• There are
– predefined data types
– system-defined types
– user-defined types
About Data Types contd.
• Predefined data types are part of the C++ language definition.
– Examples: float, double - real. int - integer. char
• We denote char literals with single quotes, for example: ‘A’ ‘*’ ‘2’
– A string literal is a sequence of characters in double quotes:
• “ABCDE”
• “127” (not the same as int 127)
• “true” (not the same as bool true)
•
•System-defined types - part of the C++ class libraries. Not part of the original
C++ language definition but added when the compiler is written.
– The standard I/O stream objects cin and cout are defined in iostream
library
– Also there is a string class (type) and classes for input and output files.
• To declare an output file: ofstream cprint (“file.txt”);
•
• User-defined types - e.g., enum type, classes
Declarations
•Declarations inform the compiler that it will need to set aside space in
memory to hold an object of a particular type (class) with a particular
name.
•
• Constant declarations
– Used to associate meaningful names with constants -- items that
will never change throughout the execution of the program.
– One convention is to use all uppercase letters for constant
identifiers.
const float PI=3.14159;
const float METERS_TO_YARDS=1.196;
Data type: char Type Casting
•We can convert char to int. The int(char) function is a cast. In this next
example, it converts c from char type to int type:
#include <iostream>
using namespace std;
void main (){
char c = 64;
cout << c << " is the same as " << int(c) << endl;
c = c+ 1;
cout << c << " is the same as " << int(c) << endl;
c = c+ 1;
cout << c << " is the same as " << int(c) << endl;
c = c+ 1;
cout << c << " is the same as " << int(c) << endl;
return;
}
• This is called typecasting – we can also cast, e.g., float(c); int(fl); …
Real number types
• A real number is a value that represents a quantity along a continuous
line.
– In C++ we can use the types float, double, and long double.
– On most systems, double uses twice as many bytes as float. In
general, float uses 4 bytes, double uses 8 bytes, and long double
uses 8, 10, 12, or 16 bytes.
– We can always use a program to determine how a type is stored on a
particular computer. The program on the next slide produced this
output:
Real number types contd.
#include <iostream>
using namespace std;
int main() {
// Creating an integer variable
int x = 25;
cout << x << endl;
// Using hexadecimal base value
x = 0x15;
cout << x;
return 0;
} 10
What Is An Array?
• An array is a collection of values that have the same data type, e.g.
– A collection of int data values or
– A collection of bool data values
• We refer to all stored values in an array by its name
• If we would like to access a particular value stored in an array, we specify
its index (i.e. its position relative to the first array value)
– The first array index is always 0
– The second value is stored in index 1
– Etc.
Classes & Object
• A class is a data type that allows programmers to create objects.
• A class is like a template,
• A class provides a definition for an object, describing an object’s
attributes (data) and methods (operations).
• An object is an instance of a class. With one class, we can have as
many objects as required.
• Object has methods, has attributes and can react to events.
Difference between Structure & Class
• As we know that Structure is a collection of variables of different
data types same as class but
• Structures are value types and the classes are reference types.
• structure have default public members and classes have
default private members
• Classes can be inherited whereas structures cannot
• A structure couldn't be null like a class
• When passing a class to a method, it is passed by reference. When
passing a structure to a method, it's passed by value
CLASS IN C++
#include<iostream>
using namespace std;
class person //class
declaration
{
public: //access specifier
char name[10];
};
int main() //main function
{
person obj; //object creation
for class
cout<<”enter the name”<<endl; //get input values for object
variables
cin>>obj.name;
cout<<obj.name; //display output
return 0;
}
STRUCTURE IN C++
#iclude<iostream.h>
#include<string.h>
using namespace std;
struct person
{
char name[10];
int age;
float salary;
};
int main()
{
person pl; //object
created for class
cout<<”enter the name”<<endl;
cin>>pl.name;
cout<<”enter age”<endl;
cin>>pl.age;
cout<<”enter salary”<<endl;
cin>>pl.salary;
cout<<pl.name<<endl<<pl.age<<end;<<pl.salary<<endl;
return 0;
Standard output
• The standard output by default is the screen, and the C++ stream object
defined to access it is cout.
• cout is used together with the insertion operator, which is written as <<
• The << operator inserts the data that follows it into the stream that
precedes it.
• Ex
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the value of x on screen
cout << "Hello"; // prints Hello
cout << Hello; // prints the content of variable Hello
Standard input
• the standard input by default is the keyboard, and the C++ stream object
defined to access it is cin.
• cin is used together with the extraction operator, which is written as >>
• The >> operator is then followed by the variable where the extracted data
is stored
• Ex:
int age, a, b;
cin >> age; // inputs a number of type int and stores it in age
cin>>a>>b ; // input two numbers ot type int and saves it in a &
Structure of C++ program
• C++ Programming language is most
popular language after C Programming
language
• Also known as C with classes
• C++ is first Object oriented programming
language.
• It has the form as shown:
Structure of C++ program
• Header File Declaration
– Header files used in the program are listed in this section
– Header File provides Prototype declaration for different library
functions.
– We can also include user define header file.
– Basically all preprocessor directives are written in this section.
• Global Declaration Section
– Global Variables are declared here, which may include -
• Declaring Structure
• Declaring Class
• Declaring Variable
Structure of C++ program
• Class Declaration Section
– Actually this section can be considered as sub section for the global
declaration section.
– Class declaration and all methods of that class are defined here.
• Main Function
– Each and every C++ program always starts with main function.
– This is entry point for all the function. Each and every method is called
indirectly through main.
– We can create class objects in the main.
– Operating system call this function automatically.
Class Declaration
• As we learned earlier
• Class is a way to bind the data and its associated functions together
• We can declare class using the syntax
class class-name
{
access specifier:
data and functions
}
• Access specifier can either private, public, protected. The "protected" is
used when inheritance is applied.
Access specifiers
• defines the access rights for the statements or functions that follows
it until another access specifier or till the end of a class. The three
types of access specifiers are "private", "public", "protected".
• private: The members declared as "private" can be accessed only
within the same class and not from outside the class.
• public: The members declared as "public" are accessible within the
class as well as from outside the class.
• protected: The members declared as "protected" cannot be accessed
from outside the class, but can be accessed from a derived class. This
is used when inheritance is applied to the members of a class.
Creating objects
• Object Instantiation:
The process of creating object of the type class
• Syntax: Creates a single object of
class_name obj_name; the classtype Student!
ex: Student st;
Student st1,st2,st3;
• Each object will have its own instances of class data and functions
Creating objects
10,Rama 20, Stephen
void read_data( ) void read_data( )
void print_data( ) void print_data( )
st st
1 2
55, Mary
void read_data( )
void print_data( )
st
Accessing Data Members & functions
• To access data members of class we use dot operator
Syntax: (single object)
obj_name.datamember;
ex: st.st_id;
st.st_name;
st.read_data();
st.print_data();
Scope resolution operator
• The scope resolution operator helps to identify and specify the context
to which an identifier refers, particularly by specifying a namespace.
• Denoted by :: (double colons)
• Can be used to
1. To access a global variable when there is a local variable with same
name
2. To define a function outside a class.
3. To access a class’s static variables.
4. to qualify hidden names
SCOPE RESOLUTION OPERATOR
• Write a C++ program to demonstrate concept of scope resolution operator?
#include<iostream.h>
#include<conio.h>
int num=20;
void main()
{
int num=10;
clrscr();
cout<<"local="<<num;
cout<<endl<<"global="<<:: num;
cout<<"global+local="<<::num+num;
}
Output:local=10
Global=20
Global+local=30
Member functions
• Member functions can be defined
– within the class definition or
– separately using scope resolution operator, ::
• To define a member function inside the class
– declares the function inline, even if you do not use the inline specifier.
• If we define the function inside class then we don't not need to declare it
first.
Member functions
• to define the member function outside the class definition
– we must declare the function inside class definition and then define it
outside.
• we have to use the scope resolution :: operator along with class name
along with function name
Syntax
• return_type class_name::function_name() {…}
• The main function for both the function definition will be same.
Friend Functions
• Friend function is a non-member function which can access the private
& protected members of a class”.
• To declare a friend function, its prototype should be included within the
class, preceding it with the keyword friend.
Syntax:
class class_name
{
//class definition
public:
friend returntype fun_name(formal parameters);
};
Friend function
#include<iostream.h>
class base
{
int val1, val2;
public:
void get()
{
cout<<”enter two values”<<endl;
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float((ob.val1+ob.val2)/2);
}
int main()
{
base obj;
obj.get();
cout<<”Mean Value is:”<<mean(obj);
return 0;
}
Output: enter two numbers: 10 20
Mean value is: 15
Friend class
• A class can also be a friend of another class, allowing access to the
protected and private members of the class in which is defined.
• Friend class and all of its member functions have access to the private
members defined within the that class.
• When a class is made a friend class, all the member functions of that
class becomes friend functions.
Friend class
• Ex
... .. ...
class B;
class A {
// class B is a friend class of class A
friend class B;
... .. ...
};
class B
{ ... ..// Now class B can access all members of A... };
Inline function
• 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.
• Any change to an inline function could require all clients of the
function to be recompiled
• To inline a function, place the keyword inline before the function
name
Inline function
Write a C++ program to demonstrate concept of scope resolution operator?
#include<iostream.h>
#include<conio.h>
int num=20;
void main()
{
int num=10;
clrscr();
cout<<"local="<<num;
cout<<endl<<"global="<<:: num;
cout<<"global+local="<<::num+num;
getch();
}
Output:local=10
Global=20
Global+local=30
This pointer
• The this pointer is an implicit parameter to all member functions
• Every object in C++ has access to its own address through an
important pointer called this pointer.
• The this pointer points to the object that invoked the function
• When a member function is called with an object, it is
automatically passed an implicit argument that is a pointer to the
invoking object (that is, the object on which the function is
called).
This pointer
• ‘this’ pointer is also used
– When local variable’s name is same as member’s name
– To return reference to the calling object
• It also prevents an object from being assigned to itself.
#include<iostream.h>
class something
{
private:
int data;
public:
something(int data)
{
tis->data=data;
}
};
Dynamic Objects
• Dynamic objects are objects that are created / Instantiated at the run
time by the class”.
• They are Live Objects, initialized with necessary data at run time.
• Its life time is explicitly managed by the program
• It can be done by new & delete
New Operator
• The new operator is used to create dynamic objects.
• We can allocate memory at run time within the heap using new operator
• It returns the address of the space allocated.
Syntax
• new data-type;
– data-type could be any built-in data type including an array or any
user defined data types include class or structure
Delete Operator
• The delete operator is used to release the memory allocated to the
dynamic objects.
• which de-allocates memory previously allocated by new operator
• delete operator does not actually delete anything
– It simply returns the memory being pointed to back to the operating
system
• Syntax
• Delete pointer;