You cannot copy content of this page.

Tag Archive OOPs

Limitations on Constructors and Destructors in C++




Limitations on Constructors and Destructors in C++

Limitations on Constructors:-

The following are the limitations on constructor functions.

  1. Constructor functions should be declared in the public section of the class.  Private and Protected constructors are available only to the member functions and friends of that class.
  2. A constructor function does not have any return type, not even void.  Hence, constructor functions can’t return any value.
  3. A constructor function may not be static.
  4. We cannot fetch the address of a constructor function.
  5. Constructors cannot be made virtual.
  6. Constructors may not be static.
  7. Constructor functions cannot be inherited.  However, a derived class can call the base class constructor.
  8. An object of a class with a constructor can’t be member of a union.
  9. The copy constructor and the default constructor are generated by the compiler only if these have not been declared for a class.
  10. Name of the constructor function must be same as that of the class.

Limitations on Destructors:

The following are the limitations imposed on destructor functions:

  1. Destructors neither take any argument nor do they return any value, not even void.
  2. Destructors cannot be inherited.
  3. It is not possible to refer to the address of a destructor.
  4. A destructor may not be static.
  5. An object of a class with a destructor cannot be a member of a union.
  6. A destructor function must have public access in the class declaration.
  7. A destructor name must be similar to that of a class, preceded by a tilde (~) symbol.


Tags,

Concept of Data hiding in a class in C++


Concept of Data hiding in a class in C++

In C++, the class groups data members and functions under three access specifiers – private, protected and public, where private and protected members remain hidden from outside world and thereby support data hiding, so that only relevant and required information is exposed to the user and rest of the unnecessary information remains hidden from the user.  The private and protected membes remain hidden from the user and the public members form an interface by providing the relevant and needed information to the outside world, which is nothing but data hiding.  Consider the following example:

class student
{
int roll_no;
public:
int rno;
void get_info()
{
roll_no = 5;
}
void put_info()
{
cout<<”Roll no = “<<roll_no;
}
};
void main(void)
{
student obj;
obj.roll_no = 5;  //results in an error //message-roll_no //not accessible.
obj.rno = 7;  // a valid assignment
obj.get_info();
}

In the above example, when the private variable roll_no is referred to by the object of the same class, it results in an error message, as a private member is accessible to only member functions.  So in order to initialize this private data member, a member function named get_info() is used, that assigns the value 5 to roll_no.  But the second assignment is perfectly a valid assignment in C++ as rno is a public variable.  Hence data members are hidden by specifying them under private section in a class.

 

Tags,

Macro vs. Inline function in C++




Macro vs. Inline function in C++

Functions considerably increase the speed of the program, when it is likely to be called many number of times.  But, if the function is small in size, then it may be defined as inline function which greatly reduces the function calling overheads.  Whenever an inline function is called, the function is inserted in the code itself rather than calling it, as is the case with normal functions.  This insertion is performed during compilation time.  Inline functions are declared like normal functions except that the function precedes with the keyword inline.

 

However, it should be noted that it is up to the wish of the compiler to make a function inline or not, even after inline specification has been given.  Also the inlining procedure will not follow if a function contains static variable or is recursive.  If a function has looping or conditional construct, and it also return value, then the inlining won’t function.


 

Macro is a preprocessor directive.  It is not really a function.  So some overheads are involved in error checking during compilation time.  When a constant is associated with a user defined symbol, that could be used in place of constant, the characters making up the constant are assigned not the numeric value of the constants.  All macros can occupy more than one line but they can not include a newline.  Macros can take arguments too.  The advantages of macros vs. functions depend on the situation.  C++ provides its own facility to define functions as inline, which have same working as that of macros, but, since they are functions, so the compiler checks for the possible errors very easily.  Further, it is upto the compiler whether to make a function inline or not, but macros, without memory consideration are expanded.  Thus in C++, inline functions prove to be much useful then macros.

Tags,

Function scope and File scope in C++




Function scope and File scope in C++

The scope for a function or a variable is determined by the place, where it is declared.  If it is defined within the body of a function then the scope is local to the function or function scope.  For example: if a function named sub() is defined inside another function named super(), then sub() can be accessed only through super().  Hence scope of sub() is local to super().

super()
{
———-
———-
sub()
{
———-
———-
}
}

Here sub() is a local function to super() and is not externally accessible.

If the above declaration of sub() function appears outside super() or all other functions, then it becomes available to all the functions in the file and the scope now is referred to as the file scope.  Thus it is accessible from anywhere in the program.  Such variables and functions which are globally available within a program are global variables and functions.  Hence

super()
{
————-
————-
}
sub()
{
————–
————–
}
Here sub() function is globally available within the program from the point of its definition.


The program demonstrating function scope and file scope is as follows:

#include <iostream.h>
#include <conio.h>
void super(void)
{
cout<<”Inside super…!”;
void sub(void)
{
cout<<”Inside sub…!”;
}
cout<<”Calling sub…!”;
sub();  // sub() function accessible
//as local to the block.
}

void main()
{
cout<<”Calling Super…!”;
super();  //function invoked as defined as a
//global function and has file scope.
cout<<”Calling Sub…!”;
sub();    // sub() function not accessible as
//it is local to the function super() and
//has function scope, thus the
//function is not accessible.
getch();
}

 

Tags,

Constructors and Destructors in C++




Constructors and Destructors in C++

Constructors:

To initialize the data members of a class, Constructors are needed.  A Constructor function is a member function that is invoked automatically when an object of the class is created.  The name of a Constructor function is similar to that of the class name.  It is used to construct data members i.e. provide initial values to the data members of the class.  The Constructors may be invoked implicitly or explicitly.  Since data members are generally defined in private section in a class, they cannot be initialized like structure variables.  So, we need a member function to perform the same job and to invoke this function automatically by the compiler and not by the programmer, its name is kept similar to that of the class.

Consider the following example:

class sample
{
int x;
int y;
public:
sample( ){x=0; y=0;}
void put_ans( )
{
cout<<”x=”<<x;
cout<<”y=”<<y;
}
};

void main()
{
sample obj; //Constructor function is called
//and x,y receive value 0.
obj.put_ans();
}

In the above example, x and y are initialized to zero, when an object obj of class sample is created.  It is confirmed by printing the values through put_ans() function.  Hence x=0 and y=0 gets displayed on the screen.

A default constructor is one, which is invoked automatically and takes no arguments.  A parameterized constructor is one that can take arguments to initialize the data member.  A copy constructor is invoked when an object is initialized with some other object of the same class.




Destructors:

Destructor is a member function that has name similiar to that of class and precedes with a tilde (~) symbol.  A destructor function neither accepts any argument nor does it return any value.  The objects that are created using constructors are destroyed using destructors.  A destructor function is called automatically when the function goes out of scope and the program terminates.  If new operator is used in constructor for allocating memory, then delete operator is used in destructors for deallocating memory.

For example:

class sample{
int x;
int y;
public:
sample()
{
x = 0;
y = 0;
}
void put_ans()
{
cout<<”x = “<<x;
cout<<”y = “<<y;
}
~sample();  // Destructor declaration.
};
sample :: ~ sample()
{
cout << “Destructor function invoked !”;
}

The above example defines a constructor and destructor for the class named sample.  When the program is about to terminate the destructor function is called and “Destructor function invoked !” message gets displayed on the screen.

Tags,

Advantages of reference variables over pointers in C++




Advantages of reference variables over pointers in C++

A reference variable is an alias to a variable already defined. After a reference variable is created, the value can be referred to by the original variable or the reference variable. Whenever we declare a reference variable, we need to initialize it at that moment. Take for example, if an ans is an int type variable, defined as:

int ans = 5;         then
int & result = ans;

result is another name of ans, by which now we can refer to the value 5.

The following assignment

result = 10;

changes the value of both the variables to 10.


To create a reference variable &(ampersand) operator is used, where & in place of representing address represents a reference to the type of variable defined.

A pointer variable is a variable that contains the addresses of some other variable. In case of pointer variables, & operator is used to fetch the address of a memory location and * (asterisk) is the de-referencing operator that fetches the value stored in a pointer variable. One has to take care of such assignments when passing or receiving this value by reference, which are not needed in case of reference variables.  Moreover reference variables are used to pass arguments to a function by reference.

Tags,

Polymorphism in C++




Polymorphism in C++

Polymorphism refers to “One Object Many Forms”. It is one of the most important features of OOPs. Polymorphism is implemented through Overloaded operators and Overloaded functions. Polymorphism can be compile time polymorphism or runtime polymorphism. In C++, polymorphism is implemented through virtual functions and dynamic binding. Early binding refers that an object is bound to its functions call at compile time. Compile time polymorphism is achieved through overloaded functions. The overloaded member functions are invoked as per their argument type and number.  For example:

int simple_interest (int principal, int rate, int time);
float simple interest (float principal, float rate, float time);

The following function call:
simple_interest (1000,5);//invokes first  prototype

Whereas the function call
simple_interest(2000,50,2.50,4.50); //Invokes the second prototype

This information is available during compile time to which function will be invoked with respect to a function call.

Run-time polymorphism is achieved through virtual functions.

For example:

class B
{
public:
virtual void func1();
}

class D : public B
{
public:
void func1();
}

void B : : func1()
{
cout<<”control in base class —-?”;
}

void D : : func1()
{
cout<<”control in derived class—–?”;
}
void main()
{
B b_obj; D d_ojj;
B *b_ptr;
b_ptr = &b_obj;
b_ptr->func1();
b_ptr = &d_obj;
b_ptr->func1();
}

If Base class function is not defined as virtual then the base class pointer always invokes the base class function irrespective of the object being pointed to by the base class pointer. But when the base class function is defined as virtual, then it is determined at run time as to invoke which function and hence is runtime polymorphism.

 

Tags,

Virtual function – Difference between a Virtual function and an Overloaded function




Virtual function

Polymorphism is the property that allows objects of different types to behave differently to the same message. In C++, polymorphism is achieved through virtual functions. Whenever we define a function with the same name in the Base class as well as in the Derived class, the base class pointer, irrespective of pointing to the desired class object, always call the base class function. If the function in the base class is defined as virtual then the function to be invoked is determined at runtime depending upon the case as to what object is being pointed to by the pointer of the base class. This is also known as runtime polymorphism or late binding or dynamic binding.




Virtual function vs. Overloaded function

A Virtual function is different from an Overloaded function. A Virtual function must have similar definitions everywhere i.e. the function prototype defined in the base class must be identical to that of the function defined in the desired class. But if two functions bear same name but different parameter list or different prototype, then they are considered as overloaded functions in place of virtual functions.

 

 

Tags,

Virtual Base class


Virtual Base Class:

A virtual base class is one that is specified as virtual when it is inherited.  If the base class definition precedes the keyword virtual, then it is referred to as virtual base class.  If a situation arises, where the data members of a base class are inherited more than once to a derived class through different inheritance paths, as in the case of hybrid inheritance, the duplication is avoided by defining the base class as virtual.  When a base class is defined as virtual, then only one copy of the members of the base class is inherited, irrespective of the existence of different inheritance paths.

An example demonstrating the use of virtual base class is given below:

Example:

#include <iostream.h>
#include <conio.h>

class teacher
{
protected:
int s_id;
public:
void get_v()
{
cout<<“\nEnter school id>”;
cin>>s_id;
}
void put_v()
{
cout<<“\nSchool id=”<<s_id;
}
};

class science : virtual public teacher
{
protected:
int science_code;
float science_marks;
public:
void get_sc()
{
cout<<“\nEnter science code?”;
cin>>science_code;
cout<<“\nEnter marks in science?”;
cin>>science_marks;
}
void put_sc()
{
cout<<“\nScience code =”<<science_code;
cout<<“\nMarks in Science =”<< science_marks;
}
};

class maths : virtual public teacher
{
protected:
int maths_code;
float maths_marks;
public:
void get_mc()
{
cout<<“\nEnter code for mathematics?”;
cin>>maths_code;
cout<<“\nEnter marks in Maths?”;
cin>>maths_marks;
}
void put_mc()
{
cout<<“\nMaths code =”<<maths_code;
cout<<“\nMarks in Maths =”<<maths_marks;
}
};

class tests_conducted : public science, public maths
{
protected:
float total_marks;
public:
void compute()
{
total_marks = science_marks + maths_marks;
}
void put_info()
{
put_v();
put_sc();
put_mc();
cout<<“\nTotal Marks =”<<total_marks;
}
};

void main()
{
clrscr();
tests_conducted test;
test.get_v();
test.get_sc();
test.get_mc();
test.compute();
test.put_info();
getch();
}

 

Tags,

'inline' keyword

Advantage of using the keyword ‘inline’ before a function:

The member functions of a class may be defined inside the class definition or outside the class using scope resolution operator. The functions defined inside a class are inline by default. Generally, the functions, which are small, are defined inside a class definition.

If a function defined outside the class intends to be inline, then inline keyword is used before the function, as shown below:

class A
{       int x;
public:
void getx();
int square(int);
};

inline int A :: square(int a)
{
return(a*a);
}

With inline keyword the function call will be replaced by the function code by the compiler. But it is upon the wish of compiler to make any function inline or not even after inline keyword is used. Only small functions should be made inline. If the functions are bigger in size, then they should be declarations normal functions. Before calling an inline function, it is required that the function is defined elsewhere.

Tags,

x Close

Like Us On Facebook