0% found this document useful (0 votes)
13 views35 pages

C++ Classes and Objects Overview

The document provides an overview of C++ programming concepts, focusing on classes and objects, encapsulation, function and operator overloading, inheritance, constructors and destructors, and friend functions and classes. It includes code examples illustrating the creation and manipulation of classes, as well as the use of member functions and access specifiers. Additionally, it explains the relationship between classes and structures, and how friend functions and classes can access private and protected members.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views35 pages

C++ Classes and Objects Overview

The document provides an overview of C++ programming concepts, focusing on classes and objects, encapsulation, function and operator overloading, inheritance, constructors and destructors, and friend functions and classes. It includes code examples illustrating the creation and manipulation of classes, as well as the use of member functions and access specifiers. Additionally, it explains the relationship between classes and structures, and how friend functions and classes can access private and protected members.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Module 1

An overview of C++
Classes and Objects
Introducing C++ Classes
The following class defines a type called stack, which will be used to create a stack.
#define SIZE 100
class stack
{
int stck[SIZE];
int tos;
public:
void init();
void push(int i);
int pop();
};
• The variables stck and tos are private. This means that they cannot be accessed by
any function that is not a member of the class.
• This is one way that encapsulation is achieved—access to certain items of data may
be tightly controlled by keeping them private.
• All variables or functions defined after public can be accessed by all other functions
in the program.
• The functions init( ), push( ), and pop( ) are called member functions because they
are part of the class stack. The variables stck and tos are called member variables (or
data members).
• Only member functions have access to the private members of their class. init( ),
push( ), and pop( ) may access stck and tos.
void stack::push(int i)
{
if(tos==SIZE)
{
cout << "Stack is full.\n"; return;

}
stck[tos] = i;
tos++;
}

Creating Objects
stack stack1, stack2;
[Link]();
• This fragment creates two objects, stack1 and stack2, and initializes stack1.
• stack1 and stack2 are two separate objects. This means, for example, that initializing
stack1 does not cause stack2 to be initialized as well.
• stack1 and stack2 are objects of the same type.

Stack class
#include<iostream>
using namespace std;
#define SIZE 100
// This creates the class stack.
class stack
{
int stck[SIZE];
int tos;
public:
void init();
void push(int i);
int pop();
};
void stack::init()
{
tos = 0;
}
void stack::push(int i)
{
if(tos==SIZE)
{
cout << "Stack is full.\n"; return;
}
stck[tos] = i;
tos++;
}
int stack::pop()
{
if(tos==0)
{
cout << "Stack underflow.\n";
return 0;
}
tos--;
return stck[tos];
}
int main()
{
stack stack1, stack2;
[Link]();
[Link]();
[Link](1);
[Link](2);
[Link](3);
[Link](4);
cout << [Link]() << " ";
cout << [Link]() << " ";
cout << [Link]() << " ";
cout << [Link]() << "\n";
return 0;
}
Function Overloading
• C++ achieves polymorphism through the use of function overloading.
• In C++, two or more functions can share the same name as long as their parameter
declarations are different.
• The functions that share the same name are said to be overloaded, and the process is
referred to as function overloading.
• Consider three functions defined by the C subset: abs( ), labs( ), and fabs( ).
• The abs( ) function returns the absolute value of an integer.
• labs( ) returns the absolute value of a long.
• fabs( ) returns the absolute value of a double.
Example 1:

#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum = " << (a + b);
}

void add(double a, double b)


{
cout << endl << "sum = " << (a + b);
}
int main()
{
add(10, 2);
add(5.3, 6.2);

return 0;
}
Example 2:
#include <iostream>
using namespace std; // abs is overloaded three ways
int abs(int i);
double abs(double d);
long abs(long l);
int main()
{
cout << abs(-10) << "\n";
cout << abs(-11.0) << "\n";
cout << abs(-9L) << "\n";
return 0;
}
int abs(int i)
{
cout << "Using integer abs()\n";
return i<0 ? –i : i;
}
double abs(double d)
{
cout <<"Using double abs()\n";
return d<0.0 ? –d: d;
}
long abs(long l)
{
cout << "Using long abs()\n";
return l<0 ? -l: l;
}
Operator Overloading
• Polymorphism is also achieved in C++ through operator overloading.
• C++ has the ability to provide the operators with a special meaning for a data type,
this ability is known as operator overloading.
• C++, it is possible to use the << and >> operators to perform console I/O operations.
They can perform these extra operations because in the header, these operators are
overloaded.

Inheritance
• In C++, inheritance is supported by allowing one class to incorporate another class
into its declaration.
• The mechanism of deriving a new class from an old one is called inheritance.
• Inheritance allows a hierarchy of classes to be built, moving from most general to
most specific.
• The process involves first defining a base class, which defines those qualities
common to all objects to be derived from the base.
• The base class represents the most general description.
• The classes derived from the base are usually referred to as derived classes.
• A derived class includes all features of the generic base class and then adds qualities
specific to the derived class.
The general form for inheritance is
class derived-class : access base-class
{
// body of new class
}
• A derived class has direct access to both its own members and the public members of
the base class
Different forms of inheritance
1)Single inheritance

2)Multilevel inheritance
3)Multiple inheritance
4)Hierarchical inheritance
5)Hybrid inheritance
#include <iostream>
using namespace std;
class student
{
protected:
int roll_number;
public:
void get_number(int);
void put_number(void);};
void student::get_number(int a)
{
roll_number=a;
}
void student::put_number()
{
cout<<"Roll Number:"<<roll_number<< "\n";
}
class test: public student
{
protected:
float sub1;
float sub2;
public:
void get_marks(float, float);
void put_marks(void);};
void test::get_marks(float x, float y)
{
sub1=x;
sub2=y;
}
void test::put_marks()
{ cout<<"Marks in SUB1="<<sub1<<"\n";
cout<<"Marks in SUB2="<<sub2<<"\n";
}
class result: public test
{
float total;
public:
void display(void);
};
void result::display(void)
{
total=sub1+sub2;
put_number();
put_marks();
cout<<"Total=" <<total<<"\n";
}
int main()
{
result student1;
student1.get_number(111);
student1.get_marks(75.0,59.5);
[Link]();
return 0;
}
Constructors and Destructors
• C++ allows objects to initialize themselves when they are created.
• This automatic initialization is performed through the use of a constructor function.
• A constructor is a special function that is a member of a class and has the same name
as that class.
• It is a special member function that initializes the objects of its class.
• In C++, constructors cannot return values and thus, have no return type.
class stack
{
int stck[SIZE];
int tos;
public:
stack(); // constructor
void push(int i);
int pop();
};
• The constructor stack( ) has no return type specified.

The stack( ) constructor is coded like this:


// stack's constructor
stack::stack()
{
tos = 0;
cout << "Stack Initialized\n";
}
• The complement of the constructor is the destructor.
• An object may need to deallocate memory that it had previously allocated or it may
need to close a file that it had opened.
• In C++, it is the destructor that handles deactivation events.
• The destructor has the same name as the constructor, but it is preceded by a ~.
• Destructors do not have return values.
// This creates the class stack.
class stack
{
int stck[SIZE];
int tos;
public:
stack(); // constructor
~stack(); // destructor
void push(int i);
int pop();
};
// stack's constructor
stack::stack()
{
tos = 0;
cout << "Stack Initialized\n"; }
// stack's destructor
stack::~stack()
{
cout << "Stack Destroyed\n";
}
The C++ Keywords
• There are 63 keywords currently defined for Standard C++.
The General Form of a C++ Program
Most C++ programs will have this general form:
#includes
base-class declarations
derived class declarations
nonmember function prototypes
int main( )
{
//...
}
non-member function definitions

Chapter 12
Classes and Objects
Classes
• Classes are created using the keyword class.
• A class declaration defines a new type that links code and data.
• This new type is then used to declare objects of that class.
• Thus, a class is a logical abstraction, but an object has physical existence.
• An object is an instance of a class.
A general form of a class declaration that does not inherit any other class.
class class-name {
private data and functions
access-specifier:
data and functions
access-specifier:
data and functions
// ...
access-specifier:
data and functions
} object-list;
• The object-list is optional. If present, it declares objects of the class.
• Here, access-specifier is one of these three C++ keywords:
public
private
protected
• By default, functions and data declared within a class are private to that class and may
be accessed only by other members of the class.
• The public access specifier allows functions or data to be accessible to other parts of
your program.
• The protected access specifier is needed only when inheritance is involved.
• char* is how you declare a pointer to a char variable. It's useful when you want a
string with unknown length.
Example: char name[10];
#include <iostream>
#include <cstring>
using namespace std;
class employee
{
char name[80]; // private by default
public:
void putname(char *n); // these are public
void getname(char *n);
private:
double wage; // now, private again
public:
void putwage(double w); // back to public
double getwage();
};
void employee::putname(char *n)
{
strcpy(name, n);
}
void employee::getname(char *n)
{
strcpy(n, name);
}
void employee::putwage(double w)
{
wage = w;
}
double employee::getwage()
{
return wage;
}
int main()
{
employee ted;
char name[80];
[Link]("Ted Jones");
[Link](75000);
[Link](name);
cout << name << " makes $";
cout << [Link]() << " per year.";
return 0;
}
• When a variable is public, it may be accessed directly by any other part of your
program.
• The syntax for accessing a public data member is the same as for calling a member
function: Specify the object's name, the dot operator, and the variable name.
• program illustrates the use of a public variable:
#include<iostream>
using namespace std;
class myclass
{
public: int i, j, k; // accessible to entire program
};
int main()
{
myclass a, b;
a.i = 100; // access to i, j, and k is OK
a.j = 4;
a.k = a.i * a.j;
b.k = 12; // remember, a.k and b.k are different
cout << a.k << " " << b.k;
return 0;
}
Structures and Classes Are Related
• A class is syntactically similar to a struct.
• The only difference between a class and a struct is that by default all members are
public in a struct and private in a class.
// C++ Program to demonstrate that Members of a class are private by default
#include <iostream>
using namespace std;
class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
return t.x;
}
// C++ Program to demonstrate that members of a structure are public by default
#include <iostream>
using namespace std;
struct Test {
// x is public
int x;
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
cout << t.x;
}
Friend Functions
• If a function is defined as a friend function in C++, then the protected and private data
of a class can be accessed using the function.
• By using the keyword friend compiler knows the given function is a friend function.
• A friend function has access to all private and protected members of the class for
which it is a friend.
• To declare a friend function, include its prototype within the class, preceding it with
the keyword friend
.
Declaration of friend function in C++:
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};
• In the above declaration, the friend function is preceded by the keyword friend.
• The function can be defined anywhere in the program like a normal C++ function.
• The function definition does not use either the keyword friend or scope resolution
operator.

#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
friend int sum(myclass x);
void set_ab(int i, int j);
};
void myclass::set_ab(int i, int j)
{
a = i;
b = j;
}
// Note: sum() is not a member function of any class.
int sum(myclass x)
{
/* Because sum() is a friend of myclass, it can
directly access a and b. */
return x.a + x.b;
}
int main()
{
myclass n;
n.set_ab(3, 4);
cout << sum(n);
return 0;
}

• The sum( ) function is not a member of myclass.


• Still has full access to its private members.
• That sum( ) is called without the use of the dot operator.
• Because it is not a member function, it does not need to be qualified with an object's
name.

3. Develop a C++ program using classes to display student name, roll number, marks obtained
in two subjects and total score of student
class student
{
private:
char name[20];
int rollno;
float sub1,sub2;
float total;
public:
void input();
void display();

};
void student::input()
{
cout<<"Enter Student Name:";
cin>>name;
cout<<"Enter Student Roll Number:";
cin>>rollno;
cout<<"Enter marks in subject1 and subject2:";
cin>>sub1>>sub2;

}
void student::display()
{
total=sub1+sub2;
cout<<"The details of the Student:";
cout<<"\nStudent Name:"<<name;
cout<<"\nStudent Roll Number:"<<rollno<<"\n";
cout<<"Marks in SUB1="<<sub1<<"\n";
cout<<"Marks in SUB2="<<sub2<<"\n";
cout<<"Total Score:"<<total;
}
int main()
{
student s;
[Link]();
[Link]();
}
Output
Enter Student Name: Vidushi
Enter Student Roll Number:54
Enter marks in subject1 and subject2: 56 78
The details of the Student:
Student Name: Vidushi
Student Roll Number:54
Marks in SUB1=56
Marks in SUB2=78
Total Score:134
Friend Classes
• It is possible for one class to be a friend of another class.
• A friend class can access private and protected members of other classes in which it
is declared as a friend.
• When this is the case, the friend class and all of its member functions have access to
the private members defined within the other class.
• We can declare a friend class in C++ by using the friend keyword.
friend class class_name; // declared in the base class
// Using a friend class.
#include <iostream>
using namespace std;
class A
{
int a=10;
int b=20;
public:
void show()
{
cout<<a<<" "<<b<<endl;
}
friend class B;
};
class B
{
public:
void add(A r)
{
int add = r.a+r.b;
cout<<"Sum of A and B:"<<add;
}
};
int main()
{
A obj;
B obj1;
[Link]();
[Link](obj);// Class A's object is obj
return 0;
}
Output:
10 20
Sum of A and B:30

// Using a friend class.


#include <iostream>
using namespace std;
class TwoValues
{
int a;
int b;
public:
TwoValues(int i, int j) { a = i; b = j; }
friend class Min;
};
class Min
{
public:
int min(TwoValues x);
};
int Min::min(TwoValues x)
{
return x.a < x.b ? x.a : x.b;
}
int main()
{
TwoValues ob(10, 20);
Min m;
cout << [Link](ob);
return 0;
}
Inline Functions
• An important feature in C++, called an inline function, that is commonly used with
classes.
• An inline function is a function that is expanded in line when it is invoked.
• The inline keyword tells the compiler to substitute the code within the function
definition for every instance of a function call. Using inline functions can make your
program faster because they eliminate the overhead associated with function calls.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
• The main use of the inline function in C++ is to save memory space.
• Whenever the function is called, then it takes a lot of time to execute the tasks, such
as moving to the calling function.
• If the length of the function is small, then the substantial amount of execution time is
spent in such overheads, and sometimes time taken required for moving to the calling
function will be greater than the time taken required to execute that function.
• Inside the main() method, when the function fun1() is called, the control is transferred
to the definition of the called function.
• The addresses from where the function is called and the definition of the function are
different.
• This control transfer takes a lot of time and increases the overhead.
• When the inline function is encountered, then the definition of the function is copied
to it.
• In this case, there is no control transfer which saves a lot of time and also decreases
the overhead.

#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);
return 0;
}
Once the compilation is done, the code would be like as shown as below:
#include<iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
return 0;
}

#include <iostream>
using namespace std;
inline int max(int a, int b)
{
return a>b ? a : b;
}
int main()
{
cout << max(10, 20);
cout << " " << max(99, 88);
return 0;
}
• Inline functions may be class member functions.
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
void init(int i, int j);
void show();
};
// Create an inline function.
inline void myclass::init(int i, int j)
{
a = i;
b = j;
}
// Create another inline function.
inline void myclass::show()
{
cout << a << " " << b << "\n";
}
int main()
{
myclass x;
[Link](10, 20);
[Link]();
return 0;
}
Defining Inline Functions Within a Class
• It is possible to define short functions completely within a class declaration.
• When a function is defined inside a class declaration, it is automatically made into an
inline function.
• It is not necessary (but not an error) to precede its declaration with the inline keyword.

#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
// automatic inline
void init(int i, int j)
{
a=i;
b=j;
}
void show()
{
cout << a << " " << b << "\n"; }
};
int main()
{
myclass x;
[Link](10, 20);
[Link]();
return 0;
}
Parameterized Constructors
• It is possible to pass arguments to constructors.
• These arguments help initialize an object when it is created.
• To create a parameterized constructor, simply add parameters to it the way you would
to any other function.
• When you define the constructor's body, use the parameters to initialize the object.
• Example: A simple class that includes a parameterized constructor:

#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
myclass(int i, int j)
{a=i; b=j;}
void show() {cout << a << " " << b;}
};
int main()
{
myclass ob(3, 5);
[Link]();
return 0;
}

Constructors with One Parameter: A Special Case


• If a constructor only has one parameter, there is a third way to pass an initial value to
that constructor.
#include <iostream>
using namespace std;
class X {
int a;
public:
X(int j) { a = j; }
int geta() { return a; }
};
int main()
{
X ob = 99; // passes 99 to j
cout << [Link](); // outputs 99
return 0;
}
Static Class Members
• Both function and data members of a class can be made static.
Static Data Members
• When you precede a member variable's declaration with static, you are telling the
compiler that only one copy of that variable will exist and that all objects of the class
will share that variable.
• No matter how many objects of a class are created, only one copy of a static data
member is created for the entire class and is shared by all the objects of that class.
• Thus, all objects of that class use that same variable.
• All static variables are initialized to zero before the first object is created.
Syntax:
• It is visible only within the class, but its lifetime is the entire program.
• When you declare a static data member within a class, you are not defining it. (That
is, you are not allocating storage for it.)
• Instead, you must provide a global definition for it elsewhere, outside the class.
• This is done by redeclaring the static variable using the scope resolution operator to
identify the class to which it belongs.
• This causes storage for the variable to be allocated.

#include <iostream>
using namespace std;
class A
{
int a;
static int b;
public:
A(int x, int y)
{
a=x;
b=y;
}
void show()
{
cout<<a<<" "<<b<<"\n";
}
static void disp()
{
cout<<b<<"\n";
}
};
int A::b=0;
int main()
{
A obj(10,20),obj2(100,200);
[Link]();
[Link]();
A::disp(); //without object access the static
data member
[Link]();
return 0;
}
Output
10 20
100 200
200
10 200
#include <iostream>
using namespace std;
class shared
{
static int a;
int b;
public:
void set(int i, int j)
{
a=i;
b=j;
}
void show();
};
int shared::a; // define a
void shared::show()
{
cout << "This is static a: " << a;
cout << "\nThis is non-static b: " << b;
cout << "\n";
}
int main()
{
shared x, y;
[Link](1, 1); // set a to 1
[Link]();
[Link](2, 2); // change a to 2
[Link]();
[Link](); /* Here, a has been changed for both x and
y because a is shared by both objects. */
return 0;
}
Output:
This is static a: 1
This is non-static b: 1
This is static a: 2
This is non-static b: 2
This is static a: 2
This is non-static b: 1
Static Member Functions
• Member functions may also be declared as static.
• There are several restrictions placed on static member functions. They may only
directly refer to other static members of the class.

#include <iostream>
using namespace std;
class cl {
static int resource;
public:
static int get_resource();
void free_resource()
{
resource = 0; }
};
int cl::resource; // define resource
int cl::get_resource()
{
if(resource) return 0; // resource already in use
else
{
resource = 1;
return 1; // resource allocated to this object
}}
int main()
{
cl ob1, ob2;
/* get_resource() is static so may be called independent
of any object. */
if(cl::get_resource())
cout << "ob1 has resource\n";
if(!cl::get_resource())
cout << "ob2 denied resource\n";
ob1.free_resource();
if(ob2.get_resource()) // can still call using object syntax
cout << "ob2 can now use resource\n";
return 0;}
Output
ob1 has resource
ob2 denied resource
ob2 can now use resource

When Constructors and Destructors Are Executed


• An object's constructor is called when the object comes into existence, and an object's
destructor is called when the object is destroyed.
• A local object's constructor is executed when the object's declaration statement is
encountered. The destructors for local objects are executed in the reverse order of the
constructor functions.
• Global objects have their constructors execute before main( ) begins execution.
• Global constructors are executed in order of their declaration, within the same file. We
do not know the order of execution of global constructors spread among several files.
• Global destructors execute in reverse order after main( ) has terminated.
• This program illustrates when constructors and destructors are executed:

#include <iostream>
using namespace std;
class myclass {
public:
int who;
myclass(int id);
~myclass();
} glob_ob1(1), glob_ob2(2);
myclass::myclass(int id)
{
cout << "Initializing " << id << "\n";
who = id;
}
myclass::~myclass()
{
cout << "Destructing " << who << "\n";
}
int main()
{
myclass local_ob1(3);
cout << "This will not be first line displayed.\n";
myclass local_ob2(4);
return 0;
}
Output
Initializing 1
Initializing 2
Initializing 3
This will not be first line displayed.
Initializing 4
Destructing 4
Destructing 3
Destructing 2
Destructing 1
The Scope Resolution Operator
• The :: operator links a class name with a member name in order to tell the compiler
what class the member belongs to.
• The scope resolution operator has another related use: it can allow access to a name in
an enclosing scope that is "hidden" by a local declaration of the same name.
int i; // global i
void f()
{
int i; // local i
i = 10; // uses local i
.
.
}
• The assignment i = 10 refers to the local i.
• But what if function f( ) needs to access the global version of i?
It may do so by preceding the i with the :: operator.
int i; // global i
void f()
{
int i; // local i
::i = 10; // now refers to global i
.
.
}
Passing Objects to Functions
• Objects are passed to functions through the use of the standard call-by value
mechanism.
• Although the passing of objects is straightforward, some rather unexpected events
occur that relate to constructors and destructors.

#include <iostream>
using namespace std;
class myclass {
int i;
public:
myclass(int n);
~myclass();
void set_i(int n)
{
i=n;
}
int get_i()
{
return i;
}
};
myclass::myclass(int n)
{
i = n;
cout << "Constructing " << i << "\n";
}
myclass::~myclass()
{
cout << "Destroying " << i << "\n";
}
void f(myclass ob);
int main()
{
myclass o(1);
f(o);
cout << "This is i in main: ";
cout << o.get_i() << "\n";
return 0;
}
void f(myclass ob)
{
ob.set_i(2);
cout << "This is local i: " << ob.get_i();
cout << "\n";
}
Output
Constructing 1
This is local i: 2
Destroying 2
This is i in main: 1
Destroying 1
• There is one call to the constructor, which occurs when o is created in main( ), but
there are two calls to the destructor.
• When the function terminates and the copy of the object used as an argument is
destroyed, the destructor is called.
Returning Objects
• A function may return an object to the caller.
• When an object is returned by a function, a temporary object is automatically created
that holds the return value.
• It is this object that is actually returned by the function. After the value has been
returned, this object is destroyed.

#include <iostream>
using namespace std;
class myclass {
int i;
public:
void set_i(int n)
{
i=n;

}
int get_i()
{
return i;
}
};
myclass f(); // return object of type myclass
int main()
{
myclass o;
o = f();
cout << o.get_i() << "\n";
return 0;
}
myclass f()
{
myclass x;
x.set_i(1);
return x;
}
Output
1
• When an object is returned by a function, a temporary object is automatically created
that holds the return value.
• It is this object that is actually returned by the function.
• After the value has been returned, this object is destroyed.

Object Assignment
• Assuming that both objects are of the same type, you can assign one object to another.
• This causes the data of the object on the right side to be copied into the data of the
object on the left.
For example, this program displays 99:

// Assigning objects.
#include <iostream>
using namespace std;
class myclass {
int i;
public:
void set_i(int n)
{
i=n;
}
int get_i()
{
return i;
}
};
int main()
{
myclass ob1, ob2;
ob1.set_i(99);
ob2 = ob1; // assign data from ob1 to ob2
cout << "This is ob2's i: " << ob2.get_i();
return 0;
}
Output
This is ob2's i: 99

You might also like