Showing posts with label constructor. Show all posts
Showing posts with label constructor. Show all posts

Friday, December 21, 2012

Constructors have to be called before the main function

Answer: yes

#include <stdio.h>
#include <conio.h>
 
/* Apply the constructor attribute to myStartupFun() so that it
    is executed before main() */

void myStartupFun (void) __attribute__ ((constructor));

 
/* Apply the destructor attribute to myCleanupFun() so that it
   is executed after main() */

void myCleanupFun (void) __attribute__ ((destructor));


/* implementation of myStartupFun */
void myStartupFun (void)
{
    printf ("startup code before main()\n");
}

/* implementation of myCleanupFun */
void myCleanupFun (void)
{
    printf ("cleanup code after main()\n");
}

int main (void)
{
    printf ("hello\n");
    return 0;
}



Monday, September 3, 2012

How do I create an instance of a class?

The methods called when a class is created are called contructors. There are four possible ways of specifying constructors; the fifth method is worth mentioning for clarifying reasons:
  • default constructor
  • copy constructor
  • value constructor
  • conversion constructor
  • copy assignment (not a constructor)
struct A
{
  A() { /* ... */ }                          // default constructor 
  A(const A &a) { /* ... */ }                // copy constructor 
  A(int i, int j) { /* ... */ }              // value constructor 
  A     &operator=(const A &a) { /* ... */ } // copy assignment 
};

struct B
{
  B() { /* ... */ }           // default constructor
  B(const A &a) { /* ... */ } // conversion constructor 
};

void    function()
{
  A     a0(0, 0); // shortcut, value constructor 
  A     a1(a0);   // shortcut, copy constructor 
  B     b1(a1);   // shortcut, conversion constructor 
  B     b;        // shortcut, default constructor 

  b1 = a0;        // conversion contructor 
  a0 = a1;        // copy assignment 
}

Thursday, August 16, 2012

What is Copy Constructor

What is a COPY CONSTRUCTOR and when is it called?
A copy constructor is a method that accepts an object of the same class and
copies it’s data members to the object on the left part of assignement.

#include <iostream>
using namespace std;

class Point2D
{
    int x; int y;

    public: int color;
    protected: bool pinned;
    public: Point2D() : x(0) , y(0) {} //default (no argument) constructor
    public: Point2D( const Point2D & ) ;
};

Point2D::Point2D( const Point2D & p )
{
    this->x = p.x;
    this->y = p.y;
    this->color = p.color;
    this->pinned = p.pinned;
}

int main()
{
    Point2D MyPoint;
    MyPoint.color = 345;
    Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color = 345
   
    cout << "\n" << AnotherPoint.color << endl;
}


OUTPUT: