0% found this document useful (0 votes)
19 views14 pages

Programming Withc& C++: Variables

The document discusses key concepts in C++ programming, focusing on data abstraction, encapsulation, and inheritance. It explains access specifiers (public, protected, private), the differences between early and late binding, and the significance of polymorphism in object-oriented programming. Additionally, it covers the role of constructors, the scope resolution operator, and the implications of multiple inheritance and virtual base classes.

Uploaded by

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

Programming Withc& C++: Variables

The document discusses key concepts in C++ programming, focusing on data abstraction, encapsulation, and inheritance. It explains access specifiers (public, protected, private), the differences between early and late binding, and the significance of polymorphism in object-oriented programming. Additionally, it covers the role of constructors, the scope resolution operator, and the implications of multiple inheritance and virtual base classes.

Uploaded by

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

197

PROGRAMMINGWITHC&C+t type by
new abstract data
PROGRAMMING WITHC& C++ languges a programmer
can define a
together with the
operations
s specifiers define how a member's structure,
variables and
unctions of a class can be accessed from outside specifying a data
structure.
the permissible on that data
However, all members of a class can be accessed from withinclass. the
class without any restriction. Data
|Structure
Class members can be declared as public protected or private
access specifiers, which is used to build the encapsulation
capabilities of the class. JOperations
There are three access specifiers. (functions)
1, Private members: These can be accessed only from within the
late binding.
members of the same class. Q8. Differentiate early versus
early
that occur at compile time
2, Protected members : These can be accessed only from withirn Early bindingrefers to events at compile time. Examples of
function
other members of the same class and its derived classes. binding means cell needed function calls, overloaded function
early binding incude normal
3. Public members : These can be accessed from anywhere where main advantage of early
calls, and over loaded operations. The function calls ar very fast.
the object is accessible. binding is efficiency and these type of
By declaring the member variables and functions as a private is late binding Late binding
The opposite of early bindingresolved
refers to function cells that are not until run time. Virtual
in aclass, the members are hidden from outside the class.Those the function
functions are used to achieve late binding. The object and binding is
private members and data cannot be accessed by the object directly. are not linked until run timne. The main advantage of late

Q.7. Define the tem data abstraction ? flexibility. Late binding allows you to create programs that carn
respond to events that occçr while the program executes without
is slow
Abstracton : Data abstraction is the technique of creating new having to create a large amount of. contingency code. It
data types. These new data types are suited for application compare toearly binding.
program. Data abstrection provides the ability to create user 0.9. What is the application of the scope resolution operator
defined data types, for modeling a real world object. The class in inC+t.
C++ is called abstract data types (ADT). Because A class is a
collection of user defined data types. C++ supports a Mechanism to access a global variable from a
function. It is achieved using the scope resolution operator. The
Abstraction refers to the act of representing essential features syntax is.
without including the background details. ::Global variable name
known
The data types created the data abstraction process are
powerful technique, The scope resolution operator permits a program to reference
as Abstract data types. Data abstraction is a
optimal, move readable, and an identifier in the global scope that has been hidden by another
and its proper usage will result in
suported by several other identifier with the same name in the local scope.
flexible program. Data abstraction is talk, Ada etc. In these
programming languages such as small
116 PROGRAMMING WITTH C&C+.
Abstraction refers to the act of representing essential featura.
without
them.
including the background details or explanation betweer
For example, a class Car would be made up of an Engine
Gearbox, Steering objects, and many more components. To build the
Car class, one does not need to know how the different
components
work internally, but only how to interface with them, i.e., send
messages to thenm, receive messages from them, and perhaps make
the different objects composing the class interact with each other.
(6) Messap e passing : It refers to that
communication between one place to another. establishing
(7) Encapsulation: The wrapping up of
into a single unit is called data and its functions
Encapsulation.
When using Data Encapsulation, daa is not
it is only accessible through the accessed directly,
functions present inside the class.
Data Abstraction increases the
power of
language by creating user defined data types. programming
represents the needed information in the programData Abstraction also
the details. without presenting
Abstraction refers to the act of representing
without including the background details or essential features
them. explanation between
For example, a class Car
would be made up of an Engine,
Gearbox, Steering objects, and many
Car class, one more
does not need to know how components. build the
To
work internally, but only how to the different
messages to them, receive interface with them,components
i.e., send
the different objects messages from them, and perhaps make
composing
Q.9. What is software
the class interact with
each other.
A reusability. Explain.
definition software reuse is the process of creating
software systems
of
The advantage offrom predefined software
(1) The software reuse: componernts.
(2) The systematic development of reusable
createsystematic
new systems.reuse of these
components components.
as building blockst
two float numbers 19.95, 20 56
Enter
19.95.
onswapping:20.56,
Explain different
Q 19. What do you mean by polymorphism ?
types of polymorphisms ?
Polymorphism:
Folymorphism means "one name, multiple forms". The term
c means the ability to have diferent objects derived from a
nmonclasS respond to the same command differently. An example
of how polymorphism is used every day in the
may point to each student and ask real world, a teacher
the question, "What is your
name"?, and expect adiferent response from each individual. In
other words, the teacher wants to
of students and send the "iterate" across an array (or) list
same message
different objects (the students) and have("What is
your name") to
each student handle the
message differently.

Polymorphism

Compile time Run time


polymorphism
polymorphism

Function over Operator over Virtual


function8
loading loading
PROGRAMMING WITH
188
polymorphism : The overloaded
Compile time
selectedfor invoking by matching arguments, member
both
functions are
and nunmber. This information is known to the compiler at the type
compiler is able to select the
compile time,
function then
appropriate
at the compile time. So this is called 'early binding" (or
polymarphism.
"Static binding" (or) Compile time
Polymorphism : The appropriate member
Runtime function
couldbe selected while the program is running, Sothis is known as
Mechanism is known as
"runtime polymorphism". This "Virtual
function", (or) late binding (or) dynamic binding, because
selection of the appropriate function is done dynamically at runtire

Q. 20. What are virtual base classes ? Explain.

Parent

Child 1 Child 2

Grand child

Consider the above, figure with a base class 'Parent'. two


derived classes. 'child1 and 'child2 and a fourth class
child', derived from both child1 and child2. The 'Grand
inherits the traits of 'Parent' via two separate grand child
inherit directly as shown by the broken line.paths. It can also
sometimes referred to as indirect base class. The parent i
All the public and
protected members of parent are inherited
into Grand child' twice, first via child 1 and again via
childz
introduces ambiguity and should be avoided. We can avoidthese
multiple paths with virtual base class, when aclass is declared as
virtual bse class, C++ take care to see that only one copy ofthat
class is inherited.
AOGRAMMING WITH C&Ct+

mean by inheritance ?
0. 13. What do you
one object car
"Inheritance": Inheritance is the process of
acquire the properties of another.

Parent Class Parent


(or) Base class Features

Parent
Child class
(or) derived features
class. Child's
features

When the class child, inherits the class


child is referred to as derived class, arnd parent, the class
class. The class child has two parts a the class parent as a base
features part. The inheritance relationderived
is
part and an child's
Because when the class child inherits the called "is-a" relation.
acquires all the properties of the parent class.base class parent. It
Feature A
Base
Feature B
Class
Feature C

Feature D Defined in derived class


Derived Feature A
Class
Feature B >Defined in base class
Feature C
PROGRAMMING WITHCC#
the "Is a" Relationship:
Inheritance can Represent
Consider the below figure, Shape is aBase class and
rounded - rectangle - shape, circle
shape, rectangle shape, these are 3
derived classes.

Shape

is a is a

Circle - Shape rectangle - shape

is a

rounded - rectangle - shape


Adrcde isa shape and a rectangle is a shape, youcan say tht
the circle -shape and rectangle - shape classes inherits from the
shape class. So inheritence is also called "is a" relation.

Q. 14. What is ambiguity inmultiple inheritance?


Multiple inheritance may. be helpful in certain cases but,
sometimes odd sort of problem encounters while using multiple
inheritance. For example: Two base classes have functions with same
name which is not overridden in derived class and if you write code
to access that function using object of derived class, compiler shows
error because, it cannot determine which function to call. Here is a
this type of ambiguity in multiple inheritance.
class basel

public:
void some_function( )
...

class base2
function properties. abstraction, encex P usefulness
data and of data score over the
concepts
implementing theThesefeatures of a 'class
from data hiding. in obiect oriented programming.
operations
ofstructure ofstructure used for
procedure-oriented
A structure is mostlv object-oriented programming
implement
while aclass is used to changes in onepart of the program donot
Moreever, it ensures that
require changes in other parts of the program.
0.6. WWhat are constructors ? Explain.
Constructors : constructor is a special member function,
A
It is special
whose task is to initialize the objects of its class. constructor is
because its name is thesame as the class namne. The
invoked whenever an object of its associated class is created. It is
of
called constructor because it construct the values of data members
the class. A constructor is declared and defined as follows.
class integer

int m, n;
public :
integer (void);

1/ constructor defined
integer :: integer (void)
m=0;
d n=0;
nd
PROGRAMMING WITHG&Gtt pA0GRAMMING WITH C& C++
115

Oriented Programming ? power etc., which form


.hatis Object Explain. manufacture, colour, top speed, engine
associated actions i.e., object
Object oriented programmingcollection
is method properties of the car class and the Methods of Car Class.No
of progamming unctions like Start, Move, Stop form the
onsidered as a of objects that Memory is allocated
where a system is certain tasks. memory is allocated when a class is created.
together to accomplish
cncapsulate data and
procedures
Objects are
that operate on the
data.
object oriented programming is
entitieinsterathatct only when an object is created, i.e., when an
created.
instance of a class is

purpose of
The main to (3) Inheritance: Inheritance is the process of forming a new
the design, programming and mostimportantly
particular data, it is
Soto modify aadditional
easy to debugging prsoimgrplam.fy
identify which,a class from an existing class or base class.

wherefuhcttoioaddn
features it is easy to identify The base class is also known as parent class or super class, the
to use. To add data.
functions and its related new class that is formed is called derived class.
elements of
Following are the basic Object Derived class is also known as a child class or sub class.
Programming (0OPS) :
Inheritance ;(4)
Oriented Inheritance helps in reducing the overallcode size of the program,
(1) Object;(2) Classes; (3) Dynamic which is an important concept in object-oriented programming.
Encapsulation Binding
(5) Polvmorphism ; (6) Message pssing ;(7) of
It is classified into different types, they are - (i) Single level
the basic unit inheritance; (ii) Multi-level inheritance ; (iii) Hybrid inheri
(1) Object: Object is
Objects are identified by its unique name. object-oriented
represents a particular instánce of a class. There can be more An
programming. thanobjoneect
tance ; (iv) Hierarchial inheritance.
(4) Dynamic binding: It contains a concept of Inheritance and
instance of an object can hold its
instance of an object. Each own Polymorphism.
relevant data.
(5) Polymorphism :
An Object is a collection of data members and associated variables of different typesPolymorphism allows routines to use
at different times. An
member functions also known as methods. function can be given different meanings or operator or
For example whenever a class name is created according to the refers to asingle function or functions. Polymorphism
class an object should be created without creating object can't able to different ways. multi-functioning operator performing in
use class. Poly a Greek term ability to take
P lace of Dog defines all possible dogs by listing ne more than one form.
Overloading 1S one type of Polymorphism. It allows an obiect to have
characteristics and behaviors they can have; the object Lassie is one different meanings,
particular dog, with particular .versions of the
charateristics. A depending on its context. When an exiting
operator or function begins to operate on new data
Dog has fur; Lassie has brown-and-white fur. understood to be overloaded. type, or class, it is
objects afe
(2) Class: Classes are data types based on which Data
grouped and its
created. Objects with similar properties and methods areindividual
abstraction
functions into
&
Encapsulation
a single
: The
wrapping up of data
represents a set of unit is called
together toform aClass. Thus a Class
objects. Characteristics of an object are represented in
a class as When
it is only using Data Encapsulation, data is not
Encapsulation.
P'roperties. The actions that can be performed by objects become accessible throughthe functions present accessed directly,
Data
Abstraction inside the class.
functions of the class and is referred to as Methods. increases the power of programming
under Wni language by creating user defined data
For example consider we have a class of cars sTepresents the needed information in thetypes. Data Abstraction also
Objects. In Abi
Santro Xing, Alto and WaganR represents individual year of the details. program without
context each Car Object will have its own, model, presenting
84 PROGRAMMING WITH C& C, PA

0. 19. What is a pointer ? Explain with the help of op


iter
example.
anothe.
Apoinler is a variable, 'consisting of address of the
variable (or) an array element. There are so many advantages of
using pointers. For example, pointers can be used to pass information
back and forth between afunction and its reference point. Pointers For
provide a-way to return multiple data items from a function via
function arguments. We can access an individual array element, using
pointers.
Suppose 'var' is a variable consisting of some data item. The
compiler will automatically assign memory cells for this data ite,
The address of 'var's memory location can be determined by the
expression of &var, where & (and symbol) is a unary operator
called the address operator that evaluates the address of its
operand. Now let us assign the address of &'var' to anothe
variable 'pvar' thus
pvar = &var

The new variable 'pvar' is called pointer to 'var'. Since i


points to the location where 'var is stored in memory. pva
represents var's address, not its value. Thus'pvar' is referred to asi
pointer variable. The relationship between 'pvar and 'var i
-illustrated in the below figure.
address of V value of V Ou
pvar Var

For example:
int var = 100; The memory location of var is 100024. Q.2
100024
100024 100
pvar var variabl
The data item is variable. 'var' can be
accessed variabl
the indirety Writ t
write
expression "pvar, where * is a called
unary operator
0tollouws the top-c++
pon apPYoach Bottor. otlow the
o does Alot Botto-up opproa
Kopport ton dons onon
tooePor
Ove Lood?nc
ouerloadnq
c you odt
ant ute in ctt

Btrote
does ot uppo ett
&uppots
ference vaiableeerence vavia ble
epexatoY overlbaorop etatoy overloo/R
&ot poss?ble Pos PoAs? ble n
arns ae

roedores ano onons and


rmodoles class
e does ot pred ett foppot, the geate
he featre of itamepue of nlame pa te
e do es lot Quppot cAt
ct Loppot
he hbeftance oheito nte
herences Between : Structures and Unions
Structure
Astructure defines a set of various types of Union
1. A union defines a set of data elements that
dataelements under a single
name. belongs to different datatypes.
Declaration
2
struct <tag>
Declaration
union <tag>
datatype memberl:
datatype member2;
datatype memberl;
datatype member2;

:Every structure member is allocated 3 The memory equivalent to the largest


memory when a structure variable is defined item is allocated commonly for all members.
Example Example
struc union tag

char c; char c;
int x:
jnt X;
ffoat y: float y:

Memory allocated for s is. The memory allocated for u is 4 bytes


|+2+4-7 bytes (Largest size among members, common
memory is used for all members).
Fat

Char
nt

value at a
4 Only once membercan be assigned
4. Althe members can be assigned values at time.
atime. may cause
Value assigned to one membermembers.
5.
5. Value assigned to one member will not the change in value of other initialized
cause the change in other members. Only one union member
can be
6. All members of astructure can be at a time.
Initialized at the same time. union un
struct st
int x;
int x; float y;
float y:
union un x = 12:
when
Struct st s= (10, 12): usage of union is efficient
th The required to be
when all members of it are nottime.
1.\Tmembers
he are actively used in the program.
usage of structure is efficient
accessed at the same
of Structures
2.3.3 Array
A
Q30. Explain thè concept of Array of structures.
Answer :
Model Papar-\, Q8a
Declaration
Arayof
is aArray of Structures
collection of similar data types. Grouping structure variables into one array is referredIto as an array of structures

Cpermits us to declare arrays of structures as shown below.


struct student

int marks1:
int marks2;
int marks3;
}st[3):
.
Where st[3]is an array of 3 elements containing three objects of student structure 1.e., each element st[3] has struchra
student with three members that are marksl, marks2 and marks3.
Usage of Array of Structures
Structure is a collection of dissimilar data types, for example in a structure for representing student information, the ideil
memhers include studentnamne, rollno, marks and it can be programmatically repre sented as shown below.
struct student

char studentname[30];
int rollno;
int marks;

In order to store data of 100 students, 100 different structure


variables say stl, st2.,... st100 i.e., struct student stl, st2,.
st100; are required. Which is definitely not very convenient. A better
data of 100 students into an array, wherein each element of array would approach would be to use an array of structures i.e., store
represent individual student information.
Example
#incude <stdio.h>i. 6i to
struct student

char sname[20];
int rolino;
fioat average,

main( )

int i;
struct student st[3] ={{"XXX", 0501,
79.6}, {"YYY, 0502, 80.3},
for(i =0;i<<2; it+) {"ZZZ", 0S03. 96.25}:

printf("n%s %d %f", st[i],sname, st[i).rollno,


st[i].average);
82
PROGRAMMING WITHG&Gt PROGRAMMING WITHC& C++ 85
Writing strings : -ta
The output function printf ( ) can be used with Examples:
os
write a string to the screen. For example, the
option( to
statement printt
s", name); can be used to display the entire contents of strcmp(namel, name2) ;
name. the array strcmp(namel, "Rao");
We can also specify the precision with which strcmp("memory'", "RAM") ;
displayed. For instance, the specification % the
string0s
first four,characters are to be printed in a field 10.4 indicates that the
width of 10 colum
Our major concerns is to determine whether the
strings are
equal ; if not, which is alphabetically above.
A8. Explain about the following string handling For example the statement
functions:
(a)strcatO (6) strcmp() (c) strepy) (d) strlen().. stremp("their", "there") ;
Will return a value of - 9 which is the numeric difference
(a) strcat ():
between ASCII "i" and ASCII "F".
The strcat() function joins
following form. two-strings together. It takes the (c) strepy ):
strcat (string 1, string 2); The strcpy () function works almost like a string - assignment
string1 and string2 are character arrays. When the operator. It takes the form strcpy (string1, string2) ;
strcat ( ) is execuied, string?2 is function And assigns the contents of string2. to string1. String2 may be a
removing the null character at theappended to string1. It does so by
end of string1 and placing string2 character array variable or a string constant. For example, the
from there. The string at strirng2 remains
Example:
unchanged. staterment

strcpy (town, "Tenali");


Let us .assume that partl has "very" and part2 has
Execution of following "good". Will assign the string "Ternali" to the string variable town.
statement Similarly, the statement
strcat (part1, part2)
will result in - strcpy (town1, town2);
partl : "very good" Will assign the contents of string variable town2 to the
string
part2:"good" variable townl. The size of array townl should be large enough to
We must make sure that the size of string1 is large enough to receive the contents of town2.
accommodate the final string. (d)' strlen)function:
(b) strcmp ) : This function counts and returns the number of
The strcmp() function compares two gs identified by the characters in å
arguments and returns a value 0 if they d. vyual. If they are, it string.
returns the numeric difference between the first nonmatching n= strlen (string);
characters in the strings. It takes the form: Where n is an integer variable which receives the value of
strcmp (stringl,string2); the length of the string. The
argunent may be a string constant. The
string! aind string2 may be string variables or string constants. COunting ends at the first null haracter.
22
PROGRAMMING WITHC& C4
multiplication and division have the same precedence we must ues
the associativity to determine the grouping. These operators
associative which means they are grouped left to right asareif left
the
expression was (a * b) /c.
Q18. What is type conversion ? Explain with an example.
Sometimes when expressions are evaluated the type of an
operand is converted. These
explicitly. Implicit conversionconversions may happen
is done automatically. implicitly
For example
or
when the operands to some operators have
smaller operand is converted to the larger different types the
One thing to note here is that operand's type.
usually perform what is called "integer operators that take integers
promotion " -converting
smaller integral types such as char and short
out the operation. Let us look at an into int before carrying
example of integer promotion:
#include <stdio.h>
void main()

char a = 100;
char b=28;
int e;
char d;

C=a+b:
d=a+b;
printf( "c=%d, d = %dn", c, d);
The output is:
C=128, d=-128
The addition operator
this environment a char is a performs implicit integer
signed 8 bit value, which promotion. On
-128 to 127. On line 10, though both a and b are has a range of
chars
converted into int before the addition is done, then the they are
result is
assigned to c, On line 11 the same thing happens, but the int result of
128 is converted báck into a char, which causes the value to
"wrap
around" to -128 since a positive 128 is not within the range of a char.

You might also like