Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit member functions of a Class in C++

Tags:

c++

The implicit member functions of a Class in C++ are: As per wiki: http://en.wikipedia.org/wiki/Special_member_functions

Default constructor (if no other constructor is explicitly declared)

Copy constructor if no move constructor or move assignment operator is explicitly declared.If a destructor is declared generation of a copy constructor is deprecated.

Move constructor if no copy constructor, move assignment operator or destructor is explicitly declared.

Copy assignment operator if no move constructor or move assignment operator is explicitly declared.If a destructor is declared generation of a copy assignment operator is deprecated.

Move assignment operator if no copy constructor, copy assignment operator or destructor is explicitly declared.

Destructor

As per link below:

http://archives.cs.iastate.edu/documents/disk0/00/00/02/43/00000243-02/lcpp_136.html

A default constructor (i.e., one with no parameters, (section 12.1 [Ellis-Stroustrup90]), if no constructor (with any number of arguments) for the class has been declared.

A copy constructor (section 12.1 [Ellis-Stroustrup90]), if no copy constructor has been declared.

A destructor (section 12.4 [Ellis-Stroustrup90]), if no destructor has been declared.

An assignment operator (sections 5.17 and 12.8 of [Ellis-Stroustrup90]), if no assignment operator has been declared.

As per link below:

http://www.picksourcecode.com/ps/ct/16515.php

default constructor

copy constructor

assignment operator

default destructor

address operator

Can some one give code examples for : Move constructor,Copy assignment operator,Move assignment operator,An assignment operator,address operator where they are being used as implicit member functions and not defined explicitly.

Thanks

like image 611
Gaurav K Avatar asked Oct 05 '22 00:10

Gaurav K


1 Answers

#include <iostream>

/* Empty struct. No function explicitly defined. */    
struct Elem
{ };

/* Factory method that returns an rvalue of type Elem. */
Elem make_elem()
{ return Elem(); }


int main() {

  /* Use implicit move constructor (the move may be elided
     by the compiler, but the compiler won't compile this if
     you explicitly delete the move constructor): */
  Elem e1 = make_elem();

  /* Use copy assignment: */
  Elem e2;
  e2 = e1;

  /* Use move assignment: */    
  e2 = make_elem();

  /* Use address operator: */    
  std::cout << "e2 is located at " << &e2 << std::endl;

  return 0;
}

The example above uses an empty class. You can fill it with data members that have real move semantics (i.e. members where moving is really different from copying), e.g. a std::vector, and you'll get move semantics automatically without defining move constructors or move assignment operators specifically for your class.

like image 103
jogojapan Avatar answered Oct 10 '22 04:10

jogojapan