Copy constructor, constructor, friend, basic idea on C ++

Source: Internet
Author: User

Any data which is declaredPrivateInside a class is not accessible from outside the class. A function which is not a member or an external class can never access such privateData. But there may be some cases, where a programmer will need access to the private data from non-member functions and external classes. c ++ offers some exceptions in such cases.

A class can allow non-member functions and other classes to access its own private data, by making themFriends. This part of C ++ tutorial essentially gives two important points.

    • Once a non-member function is declared as a friend, it can access the private data of the class

    • Similarly when a class is declared as a friend, the friend class can have access to the private data of the class which made this a friend

Let's see a sample in this c ++ tutorial for each of the above cases.

C ++ tutorial-friend function sample:

# Include <iostream. h>
// Declaration of the function to be made as friend for the c ++ tutorial sample
Int addtofriend (int x );
Class cpp_tutorial
{
Int private_data;
Friend int addtofriend (int x );
Public:
Cpp_tutorial ()
{
Private_data = 5;
}
};
Int addtofriend (int x)
{
Cpp_tutorial var1;
Return var1.private _ DATA + X;
}
Int main ()
{
Cout <"added result for this c ++ Tutorial:" <addtofriend (4) <Endl;
}

The output of the above C ++ tutorial sample will be
Added result for this c ++ Tutorial: 9

C ++ tutorial-friend class:

Declaration of a friend class is also similar. Only thing is a class definition is slightly different.

C ++ tutorial-friend function:

# Include <iostream. h>
Class cpp_tutorial
{
Int private_data;
Friend class friendclass;
Public:
Cpp_tutorial ()
{
Private_data = 5;
}
};
Class friendclass
{
Public:
Int subtractfrom (int x)
{
Cpp_tutorial var2;
Return var2.private _ data-X;
}
};
Int main ()
{
Friendclass var3;
Cout <"added result for this c ++ Tutorial:" <var3.subtractfrom (2) <Endl;
}

The output of the above C ++ tutorial sample will be
Subtracted result for this c ++ Tutorial: 3

This is a good way out given by C ++ to avoid restrictions on private variables. but this shoshould be used with caution though. if all the functions and classes are declared as friends, then the concept of encapsulation and data security will go for a toss.

That is why the concept of friend functions and classes shocould be used with proper judgment.

 

 

Operator OverloadingIs a beautiful concept in C ++. At times it is little confusing also. But actually they are quite easy. Anyway, here is an example for overloading the stream operators.

The best way to overload the stream operators is not to make them members of any class, but to keep them as friends. i. E ., wherever there is a need to use the stream operators, use them as friend functions with the suitable parameters.

The following example shows the use of these operators forClass.

# Include <iostream. h>
# Include <string. h>
Class base
{
Char strval [100];
Public:
Base () {strcpy (strval ,"");}
Base (char * val) {strcpy (strval, Val );}
~ Base () {* strval = '\ 0 ';}
Friend istream & operator> (istream & is, base & OBJ );
Friend ostream & operator <(ostream & OS, const base & OBJ );
};
Istream & operator> (istream & is, base & OBJ)
{
Is> strval;
Return is;
}
Ostream & operator <(ostream & OS, const base & OBJ)
{
OS <obj. strval;
Return OS;
}
Void main ()
{
Base B;
Cin> B;
Cout <"printing the value \ n ";
Cout <B <Endl;
}

If there are derived classes which need to use the stream operators, one way is to define some more versions of the stream operators withDerived classParameters.

 

Copy constructor is

    • A constructor function with the same name as the class
    • Used to make deep copy of objects.

There are 3 important places where a copy constructor is called.

    1. when an object is created from another object of the same type
    2. when an object is passed by value as a parameter to a function
    3. when an object is returned from a function

If a copy constructor is not defined in a class, the compiler itself defines one. this will ensure a shallow copy. if the class does not have pointer variables with dynamically allocated memory, then one need not worry about defining a copy constructor. it can be left to the compiler's discretion.

But if the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor.

For ex:
Class A // without copy constructor
{
PRIVATE:
Int X;
Public:
A () {A = 10 ;}
~ A (){}
}

Class B // with copy constructor
{
PRIVATE:
Char * Name;
Public:
B ()
{
Name = new char [20];
}
~ B ()
{
Delete name [];
}
// Copy constructor
B (const B & B)
{
Name = new char [20];
Strcpy (name, B. Name );
}
};

Let us imagine if you don't have a copy constructor for the Class B. at the first place, if an object is created from some existing object, we cannot be sure that the memory is allocated. also, if the memory is deleted in destructor, the delete operator might be called twice for the same memory location.

This is a major risk. one happy thing is, if the class is not so complex this will come to the fore during development itself. but if the class is very complicated, then these kind of errors will be difficult to track.

In Windows this will lead to an application popup andUNIXWill issue a core dump. A careful handling of this will avoid a lot of nuisance.

A class in C ++ is an encapsulation of data members and functions that manipulate the data. The class can also have some other important Members which are already turally important.

This C ++ tutorial discusses the components of a C ++ class. More C ++ tutorials will follow.

C ++ tutorial-class data members:

Very important point about the data members in this c ++ tutorial! This title is not a keyword or a data type in C ++. This is just to explain one of the logical classifications of the types of members that are available in C ++.

TheDataMembers can be of any legalData Type, A class type, a struct type etc ., they can also be declared as pointers and accessible normally as like other data members. the example class given below in this c ++ tutorial has two data members X and Y of type Integer.

C ++ tutorial-function members in classes:

Functions declared inside a class can be any of the following four types. This C ++ tutorial explains each one of them as below.

Ordinary member functions:

These are ordinary functions defined with a return type and parameters. The return type can also be void. The special trait aboutMemberFunctions is they can access the private/protected data members of their class and manipulate them. no external functions can access the private/protected data members of a class. the sample below this c ++ tutorial uses an ordinary member function add (), returning an integer value.

Constructors:

Constructors in C ++ are special member functions of a class. they have the same name as the class name. there can be any number of overloaded constructors inside a class, provided they have a different set of parameters. there are some important qualities for a constructor to be noted.

    • constructors have the same name as the class.

    • constructors do not return any values

    • constructors are invoked first when a class is initialized. any initializations for the class members, memory allocations are done at the constructor.

In the example class given below in this c ++ tutorial has the constructor example_class (), with the same name as the class.

Destructors:

Destructors in C ++ also have the same name, should t for the fact that they are preceded by '~ 'Operator. the Destructors are called when the object of a class goes out of scope. it is not necessary to declare a constructor or a destructor inside a class. if not declared, the compiler will automatically create a default one for each. if the constructor/destructor is declared as private, then the class cannot be instantiated. check below for the sample class of the C ++ tutorial for an example of destructor.

C ++ tutorial-access level:

The classes in C ++ have 3 important access levels. They arePrivate, publicAndProtected. The explanations are as follows.

PRIVATE:

The members are accessible only by the member functions or friend functions.

Protected:

These members are accessible by the member functions of the class and the classes which are derived from this class.

Public:

Accessible by any external member. Look at the sample class below.

C ++ tutorial-Example of a class:

Class example_class // sample class for the c ++ tutorial
{
PRIVATE:
Int X; // data member
Int y; // data member
Public:
Example_class () // constructor for the c ++ tutorial
{
X = 0;
Y = 0;
}
~ Example_class () // destructor for the c ++ tutorial
{}
Int add ()
{
Return X + Y;
}
};

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.