Class Notes

21
SATHYABAMA UNIVERSITY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 6C0094 – PROGRAMMING IN C++ SYLLABUS UNIT – I Introduction to fundamental Concepts : Object oriented fundamentals, Structured verses Object oriented development, elements of object oriented programming, fundamentals of OOP - class, object, and abstraction and its importance, encapsulation, polymorphism, benefits of OOP, structure of C++ program. UNIT – II Classes and Objects: Working with classes - classes and objects - class specification, class objects, accessing class members, defining member functions, inline functions, accessing member functions within class, data hiding, class member accessibility, empty classes, constructors, parameterized constructors, constructor overloading, copy constructors, new, delete operators, “this” pointer, friend classes and friend functions. UNIT – III Overloading: Function overloading, operator overloading, overload able operators, unary operator overloading, operator keyword, limitations of increment/ decrement operators, binary operator overloading, arithmetic operators, function templates, class templates. UNIT – IV Inheritance: Base class and derived class relationship, derived class declaration, forms of inheritance, inheritance and member accessibility, constructors in derived class, destructors in derived class, multiple inheritance, multi 1

Transcript of Class Notes

Page 1: Class Notes

SATHYABAMA UNIVERSITY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

6C0094 – PROGRAMMING IN C++

SYLLABUS

UNIT – IIntroduction to fundamental Concepts : Object oriented fundamentals, Structured verses Object oriented development, elements of object oriented programming, fundamentals of OOP - class, object, and abstraction and its importance, encapsulation, polymorphism, benefits of OOP, structure of C++ program.

UNIT – IIClasses and Objects: Working with classes - classes and objects - class specification, class objects, accessing class members, defining member functions, inline functions, accessing member functions within class, data hiding, class member accessibility, empty classes, constructors, parameterized constructors, constructor overloading, copy constructors, new, delete operators, “this” pointer, friend classes and friend functions.

UNIT – IIIOverloading: Function overloading, operator overloading, overload able operators, unary operator overloading, operator keyword, limitations of increment/ decrement operators, binary operator overloading, arithmetic operators, function templates, class templates.

UNIT – IVInheritance: Base class and derived class relationship, derived class declaration, forms of inheritance, inheritance and member accessibility, constructors in derived class, destructors in derived class, multiple inheritance, multi level inheritance, hybrid inheritance, virtual base classes, virtual functions.

UNIT – VException handling and files: Files and streams, opening and closing of files, file modes, file pointers and manipulation, sequential access to a file, binary file, random access to a file, error handling during file manipulation, exception handling, exception handling model, exception handling constructs, list of exceptions, catching exceptions, handling exceptions.

1

Page 2: Class Notes

REFERENCE BOOKS:

1. K.R. Venu Gopal, T. Ravishankar, and Raj kumar, “Mastering C++”, Tata McGraw Hill, 1997.

2. E. Balaguruswamy, “Object Oriented Programming with C++”, Tata McGraw Hill, 2nd Edition, 2004.

3. Bjarne Stroustrup, “The C++ programming language”, Addison Wesley, 3rd

Edition, 1998.4. John R Hubbard, Programming with C++, 2nd edition Shaums Outline

Series, McGraw Hill5. James Martin & james J.Odell, Object Oriented methods – A foundation,

Prentice Hall, 19976. Grady Booch, Object Oriented Analysis and Design with application, II

Edition Addision Wesley, 1994

2

Page 3: Class Notes

UNIT – I (2 MARKS)

1. Characteristics of procedure oriented programming (c)

Emphasis is on doing things (algorithms)Larger programs are divided into smaller programs known functions.Most of the functions share global data.Data move openly around the system from function to functionsFunctions transforms data from one form to another Employs TOP-DOWN approach in program design.

2. Characteristics of object oriented programming (c++)

Emphasis is on data rather than procedure.Programs are divided into what known as OBJECTSData structures are designed such that they characterize the objectsFunctions that operate on the data of an object are tied together in the data structure.Data is hidden and cannot be accessed by external functions.Objects may communicate with each other through functions New data and functions can be easily added whenever necessaryFollows BOTTOM-UP approach in program design

3. What are difference between c and c++?

S.No Procedure oriented Programming (C) Object Oriented Programming (C++)

1.

2.

3.

4.

5.

Programs are divided into smaller sub-programs known as functions

Here global data is shared by most of the functions

It is a Top-Down Approach

Data cannot be secured and available to all the function

Here, the reusability is not possible, hence redundant code cannot be avoided.

Programs are divides into objects & classes

Objects are easily communicated with each other through function.

It is a Bottom-Up Approach

Data can be secured and can be available in the class in which it is declared

Here, we can reuse the existing one using the Inheritance concept

3

Page 4: Class Notes

4. Define encapsulation:

It is the mechanism that associates the code and data it manipulates into a single unit and keeps them safe from external interference and misuse. In C++, this is supported by the construct called CLASS

5. Define inheritance :

It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance involves the creation of new classes from the existing ones. The new derived class inherits the members of the base-class and also adds its own.

Popular forms : 1. Single Inheritance 2. Multiple Inheritance

6. Define polymorphism:

One name multiple formsA property by which we can send the same message to objects of several different classes, and each object can respond in a different way depending on its class. In C++ polymorphism is implemented by means of function overloading and operator overloading and by means of virtual functions.

7. Define classes:

A group of objects that share common properties and relationships. In C++, class is a new datatype that contains member variables and member functions that operate on the variables.

8. Define object:

Objects are basic runtime entities in an object oriented system. They may represent a person, a plea, a bank account etc. An instance of the calss is known as object.

9.Define message passing:

It is the process of invoking an operation on an object. In response to the message, the corresponding method is executed in the object.

10.Define data abstraction:

Abstraction refers to the act of representing essential features without including background details or explanations.The technique of creating new data types that are well suited to an application to be programmed is known as data abstraction.

4

Page 5: Class Notes

1. Write a c++ program to read 2 numbers from the keyboard and display large value on the screen

#include<iostream.h>void main()

{int a,b;cin>>a>>b;if(a>b)

cout<<a;else

cout<<b;}

2. Define inline function.

An inline function is a function that is expanded inline when it is invoked. That is the compiler replaces the function call with the corresponding function code

Syntax:Inline function header

{function body

} 3. When we need inline functions?

Whenever the function is called, it takes a lot of extra time in executing a series of instructions for tasks such as a jumping to the functions, saving registers, pushing arguments onto the stack, and returning to the calling function. When the function is small, a substantial – percentage of execution time may be spent in such overloads.To eliminate the cost of calls to small functions, We are using Inline functions.

4. How to access a class members:

Once an object of a class has been created, there must be a provision to access its members. This is achieved by using the member access operator, dot(.).

Syntax: for accessing datamember of a class

Object name . datamember

5Name of the class defined object

Member access specifier

datamember of a class

Page 6: Class Notes

5. Defining member function

The data members of a class must be declared within the body of the class, whereas the member functions of the class can be defined in any one of the following ways.

Inside the class specification Outside the class specification

The syntax of a member function definition changes depending on whether it is defined inside or outside the class specification, but it performs the same operation.

6. What is the application of scope resolution operator in c++?It allows to access the global version of the variable. In C, the global version of

the variable cannot be accessed from within the inner block. C++ resolves this problem by introducing the new operator :: called the scope resolution operator. This is used to recover the hidden variable. IT takes the following form

:: variable name7. Purpose of setw

setw is one of the manipulator. It is used to specify the width for the value of the variable and the value is automatically right justified

8. How does the c++ structure differs from c++ class?

The main difference between structure and a class in C++ is that, by default, the members of the class are private, while by default the members of structure are public.

9. Define friend function.(how to access the private data of the class)

A non-member function can access the private data of the class if it is declared as a friend to that class. Such a type of function is called friend function.

Syntax.Class abc

{public:

friend void xyz(void);}

Now the function xyz() can access the private data of the class abc

6

Page 7: Class Notes

10. Define constructor.

A constructor is a special member function whose main operation is to allocate the required resources such as memory and initialize the objects of its class. The constructor is invoked whenever an object of its associated class is created.

1. What do you mean operator overloading?

*The operator overloading feature of C++ is one of the methods of realizing polymorphism. *The mechanism of giving special meaning to an operator is known as operator overloading. *It extends the semantics of an operator without changing its syntax.

2. List the operators that cannot be overloaded.

1.sizeof operator(Sizeof( )) 2.Member access operators(dot operator) 3.Scope Resoulation operator(::) 4.Conditional operator(?:)

. 3. What is an operator function?

To define an additional task to an operator,we must specify what it means in relation to the class to which the operator is applied.This is done with the help of the special function known as operator function. Syntax: Return type classname::operator op(arg) {

}operator->keyword.op ->operator to be overloaded.

4. What do u mean by unary & binay operator overloading?

Unary:Overloading without explict arguments to an operator function is known as unary operator overloading. Syntax: Return type operator operator symbol() { } Binary: overloading with a explicit single argument is known as binary operator overloading. Syntax:

7

Page 8: Class Notes

Return type operator operator symbol(arg) { }

5. Define templates.

A template can be considered as a kind of macro.when an object of a specific type is defined for actual use,the template definition for that class is substituted with thw required data type. Since a template is defined with the parameter that would be replaced by the specified datatype at the time of actual use of the class ar function,the templates are sometimes called parameterized classes or functions.

6. Define function templates.

Templates declared for functions are called function templates.Thus we can make the same function performs the same operation for different datatypes. Syntax: Template<class t,> Return type function name(arg) { } template->keyword. t->template type argument arg->one of the arguments must be template data type.

7. Write the function template for swapping two values the values must be generic datatype.

Template<class t> Void swap(t x,t y) { t t1; t1=x;

x=y;y=t1;

}

8. Define class templates.

Templates declared for classes are called class templates.Thus we can make the single class to perform the same operation on different data types.

Syntax: Template<class t>

8

Page 9: Class Notes

Class classname { //class member specification with anonymous type t whenever appropriate };

9. Define destructor:

A destructor is used to destroy the objects that have been created by the constructor. Destructor name is same as the class name but it is preceded by the tilde symbol.

Eg: Class A{public:

~A() // destructor{}

};

10. List some of the special properties of constructors

1. Constructor name is same as class name2. It is invoked automatically when the object of its class is created3. They do not have return types4. They should be declared under public section.

11. Difference between constructor and destructor

12. What do you mean by “this pointer.”

The keyword this is the pointer variable which always contains the address of the object in question (ie) each member function of the class is born with this pointer, which points to the object with which the member function is associated.This pointer can be used to access the data in the object is points to.Eg:

Class a{private:

int a;

9

CONSTRUCTOR DESTRUCTOR

1. Name is same as class name 1. Name is same as class name but it is preceded by the tilde symbol

2. Arguments can be passed to the 2. Arguments cannot be passed to the constructor destructor3. Constructor cannot be overloaded 3. Cannot be overloaded4.constructor is called whenever the 4.destructor is called when the object is object is created destroyed

Page 10: Class Notes

public”void getdata()

{cin>>a;

}void putdata()

{cout<<a;cout<<this a // can access the value of “a “using “this”

pointer.same as the value of a}

};

1. What is meant by Base class? The mechanism of deriving a new class from an old one is called inheritance the old class is referred to as the base class.

2. What is meant by derived class?

The mechanism of deriving a new class from an old one is called inheritance . the old class is referred to as the base class and the new one is called the derived class. the derived class inherits some of the traits properties of the base class.

Defining derived class

A derived class is defined by specifying its relationship with the base class in addition to its own details. The general for m of defining a derived class is

Class derived class name : visibility mode base class name{members of derived class};

The colon indicates that the derived class name is derived from the base class name. The visibility mode is optional and , if present , may be either private or public. The default visibility mode is private.

10

Page 11: Class Notes

3. What do you mean by Hybrid inheritance? Multiple + hierarchical is called as hybrid inheritance

Base A

Derived B1

Derived B2

Derived C

4. What do you mean by Virtual Base Class?

When three kind’s of inheritance occurs the child will have two direct base class’s parent1 and parent2 which they themselves have a common base class grand parent, which grandparent is sometimes referred to as indirect inheritance by the child. The child would have duplicate sets of the members inherited from grandparent and this should be avoided.

The duplication of member’s can be avoided by making the common base class as virtual base class while declaring the direct or intermediate base class as shown below.

grandparent

Parent

parent

child

5. What do you mean by Virtual functions?

As told earlier polymorphism refers to the property is which objects belonging to different classes are able to respond to the same message, but in different forms. When even when the object of the derived class is created it executes only the member functions of the base class. This drawback is over come using these virtual functions, by naming the base class functions using a keyword virtual followed by the normal declaration.

11

Page 12: Class Notes

6. What is multilevel inheritance?

The mechanism of deriving a class from derived class is known as multilevel inheritance

A

B

C

7. Define Multiple Inheritances?

The derived class with with more than one base class is called multiple inheritance

Base class 1

Baseclass2

Derived class

The general syntax for derived class with multiple base class is as follows

Class derived : visibility b1,visibility b2,……..{

body of derived};

1. What is a stream?

A stream is a sequence of bytes .It acts either as a sourcr from which the input data can be obtained or as a destination to which the output data can be sent. The source stream that provides data to the program is called input stream and the destination stream that receives output from the program is called output stream.

12

Page 13: Class Notes

2. Explain how While(fin) statement detects the end of the file connected to the fin stream? While(fin)

An ifstream object,such as fin,returns a value 0 if any error occurs in the file operation operation including the end of the file condition.Thus the while loop terminates when fin returns the value zero on reaching the end of file condtion.

3. What is a file mode?Describe the various file mode option available. Filemode which specifies the purpose for which the file is opened. Various file modes Ios::app append to the end of the file. Ios::ate go to yhe end of the file on opening. Ios::binary binary file

Ios::in open file for readingIos::out open file for writing

Ios::trunc delete the contents of the file if it exists.

4. .What is an exception? Exceptions are run time anomalies or unusual conditions that the program may encounter while executing,Anomalies might include the conditions such as division by zero,access to an array outside of its bounds etc.

5. How is an exception handled in C++? Exception handling code performs the following tasks. 1.find the problem(hit the exeception) 2.inform that anerror has occurred(throw the exception)

3.Receive the error information(catch the exception) 4.take the corrective actions(Handle the exception)

6. What should be placed in the try and catch block. The keyword try is used to preface the block of statements which may generate exceptions.when an exception is detected ,it is thrown using a throw statement in the try block. A catch block defined by the keyword catch catches the exception thrown by the throw statement and handles the appropriately.

7.. what are all the major elements of the object oriented model?

Abstraction Encapsulation Modularity

Hierarchy

13

Page 14: Class Notes

8.What are all the minor elements of an object oriented model?

Typing Concurrency Persistence

9.Define abstraction.An abstraction denotes the essential characteristics of an object that distinguish it

from all other kinds objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.

10.Define encapsulation

Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior encapsulation serves to separate the contractual interface of an abstraction and its implementation

11.what do u mean modularity? Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules

12.Define the element typing. Typing is the enforcement of the class of an object such that objects of different types may not be interchanged or at the most, they may be interchanged only in very restricted ways.

13.Define the term persistance. Persistence is the property of an object through which its existence transcends time (i.e. the object continues to exist after its creator ceases to exist) and/or space (ie. The object’s location moves from the address space in which it was created)

14.what are all the properties of an object. 1. State 2. Behavior 3.Operations 15.What are all the basic kinds of relationships among classes:

Generalization/specialization - “ is a “ Whole/Part (aggregation) - “ part of “ association - some semantic dependency among classes

16.what are all the other relationships between classes.

1. Association

14

Page 15: Class Notes

2. Inheritance3. Aggregation4. Using5. Instantiation6. Meta-Class

17.Define the term cardinality. Multiplicity relationship existing between the classes is called cardinality.

one to one: narrow association, sale-bill-one credit card transaction one to many: Sales and products Many to Many:Customer interactions with sales person

18.what do u mean metaclass?A metaclass is a class where instances are themselves classes.

19.What do u mean classification. Classification is the means by which we order knowledge. In simple words the process of classification is the process of identifying commonness among different objects and grouping different objects on the basis of one or more properties.

20. GENERAL APPROACHES TO CLASSIFICATION(important)

Classical categorization

Conceptual clustering

Prototype Theory

15