C++ Tutorial/Class/constructor

Материал из C\C++ эксперт
Перейти к: навигация, поиск

A parameterized constructor

<source lang="cpp">#include <iostream> using namespace std;

class MyClass { public:

 int x; 

 MyClass(int i);  // constructor 
 ~MyClass();      // destructor 

};

// Implement a parameterized constructor. MyClass::MyClass(int i) {

   x = i; 

}

// Implement MyClass destructor. MyClass::~MyClass() {

 cout << "Destructing object whose x value is " << x  <<" \n"; 

}

int main() {

 MyClass t1(5); 
 MyClass t2(19); 

 cout << t1.x << " " << t2.x << "\n"; 

 return 0; 

}</source>

5 19
Destructing object whose x value is 19
Destructing object whose x value is 5

Call class constructor or not during class array declaration

<source lang="cpp">#include <iostream>

  1. include <new>

using namespace std; class powers {

 int x;

public:

 powers() {
    x = 0;
    cout << "\nno initializer\n\n";
 }
 powers(int n) {
    x = n;
    cout << "\n\ninitializer:" << x;
 }
 int getx() { return x; }
 void setx(int i) { x = i; }

}; int main() {

 powers ofTwo[] = {1, 2, 4, 8, 16}; // initialized
 powers ofThree[5];                 // uninitialized

}</source>

initializer:1
initializer:2
initializer:4
initializer:8
initializer:16
no initializer

no initializer

no initializer

no initializer

no initializer

Call constructor from base class to initialize fields inherited from base class

<source lang="cpp">#include <iostream> using namespace std; class base { protected:

 int i;

public:

 base(int x) { 
    i=x; 
    cout << "Constructing base\n"; 
 }
 ~base() { 
    cout << "Destructing base\n"; 
 }

}; class derived: public base {

 int j;

public:

 derived(int x, int y): base(y){ 
    j=x; 
    cout << "Constructing derived\n"; 
 }
 ~derived() { 
    cout << "Destructing derived\n"; 
 }
 void show() { 
    cout << i << " " << j << "\n"; 
 }

}; int main() {

 derived ob(3, 4);
 ob.show();
 return 0;

}</source>

Constructing base
Constructing derived
4 3
Destructing derived
Destructing base

Call default constructor when allocating an array dynamically

<source lang="cpp">#include <iostream>

  1. include <new>

using namespace std; class powers {

 int x;

public:

 powers() {
    x = 0;
    cout << "\nno initializer\n\n";
 }
 powers(int n) {
    x = n;
    cout << "\n\ninitializer:" << x;
 }
 int getx() { return x; }
 void setx(int i) { x = i; }

}; int main() {

 powers *p;
 // dynamically allocate an array
 try { 
   p = new powers[5]; // no initialization
 } catch (bad_alloc xa) {
     cout << "Allocation Failure\n";
     return 1;
 }

}</source>

no initializer

no initializer

no initializer

no initializer

no initializer

Constructor as conversion operator

<source lang="cpp">#include <iostream>

class MyType
{
public:
    MyType();
    MyType(int val);
    ~MyType(){}
    int getValue()const { return myValue; }
    void setValue(int x) {myValue = x; }
private:
    int myValue;
};

MyType::MyType(): myValue(0) {}

MyType::MyType(int val): myValue(val) {}

int main()
{
    int theShort = 5;
    MyType theCtr = theShort;
    std::cout << "theCtr: " << theCtr.getValue() << std::endl;
    return 0;
}</source>
theCtr: 5

Constructor parameter with default value

<source lang="cpp">#include <iostream>

  1. include <iomanip>

using namespace std; class MyClass {

public:
  MyClass(int a = 1, int b = 2, int c = 3){
       MyClass::a = a; 
       MyClass::b = b;
       MyClass::c = c;
  };
  void show_numbers(void){ 
      cout << a << " " << b << " "<< c << "\n"; 
  };
private:
  int a, b, c;

}; int main(void){

  MyClass one(1, 1, 1);
  MyClass defaults;
  MyClass happy(101, 101, 101);
  one.show_numbers();
  defaults.show_numbers();
  happy.show_numbers();

}</source>

Copy constructors

<source lang="cpp">#include <iostream>

class MyClass
{
public:
    MyClass();                          // default constructor
    MyClass (const MyClass &);          // copy constructor
    ~MyClass();                         // destructor
    int GetAge() const { return *itsAge; }
    int GetWeight() const { return *itsWeight; }
    void SetAge(int age) { *itsAge = age; }

private:
    int *itsAge;
    int *itsWeight;
};

MyClass::MyClass()
{
    itsAge = new int;
    itsWeight = new int;
    *itsAge = 5;
    *itsWeight = 9;
}

MyClass::MyClass(const MyClass & rhs)
{
    itsAge = new int;
    itsWeight = new int;
    *itsAge = rhs.GetAge();
    *itsWeight = rhs.GetWeight();
}

MyClass::~MyClass()
{
    delete itsAge;
    itsAge = 0;
    delete itsWeight;
    itsWeight = 0;
}

int main()
{
    MyClass myObject;
    std::cout << "myObject"s age: " << myObject.GetAge() << "\n";
    std::cout << "Setting myObject to 6...\n";
    myObject.SetAge(6);
    std::cout << "Creating secondObject from myObject\n";
    MyClass secondObject(myObject);
    std::cout << "myObject"s age: " << myObject.GetAge() << "\n";
    std::cout << "secondObject" age: " << secondObject.GetAge() << "\n";
    std::cout << "setting myObject to 7...\n";
    myObject.SetAge(7);
    std::cout << "myObject"s age: " << myObject.GetAge() << "\n";
    std::cout << "boot"s age: " << secondObject.GetAge() << "\n";
    return 0;
}</source>
myObject"s age: 5
Setting myObject to 6...
Creating secondObject from myObject
myObject"s age: 6
secondObject" age: 6
setting myObject to 7...
myObject"s age: 7
boot"s age: 6

Defining and using a default class constructor

<source lang="cpp">#include <iostream>

  1. include <iostream>

using std::cout; using std::endl; class Box {

 public:
   double length;
   double width;
   double height;
   Box() {
     cout << "Default constructor called" << endl;
     length = width = height = 1.0;          // Default dimensions
   }
   
   Box(double lengthValue, double widthValue, double heightValue) {
     cout << "Box constructor called" << endl;
     length = lengthValue;
     width = widthValue;
     height = heightValue;
   }
   
   double volume() {
     return length * width * height;
   }

};

int main() {

 Box firstBox(80.0, 50.0, 40.0);
 Box smallBox;
 return 0;

}</source>

Box constructor called
Default constructor called

If a constructor only has one parameter

<source lang="cpp">#include <iostream> using namespace std;

class X {

 int a;

public:

 X(int j) { a = j; }
 int geta() { return a; }

};

int main() {

 X ob = 99; // passes 99 to j
  
 cout << ob.geta(); // outputs 99
  
 return 0;

}</source>

Initialize variables and conduct calculation in constructor

<source lang="cpp">#include<iostream.h> class box {

  double line,width,heigth;
  double volume;

public:

  box(double a,double b,double c);
  void vol();

}; box::box(double a,double b,double c) {

  line=a;
  width=b;
  heigth=c;
  volume=line*heigth;

} void box::vol() {

  cout<<"Volume is:"<<volume<<"\n";

} main() {

  box x(3.4,4.5,8.5),y(2.0,4.0,6.0);
  x.vol();
  y.vol();
  return 0;

}</source>

Volume is:28.9
Volume is:12

overload constructor

<source lang="cpp">#include <iostream>

  1. include <cstdio>

using namespace std; class date {

 int day, month, year;

public:

   date(char *d)
   {
     sscanf(d, "*c*cd", &month, &day, &year);
   }
   
   date(int m, int d, int y)
   {
     day = d;
     month = m;
     year = y;
   }
   
   void show_date()
   {
     cout << month << "/" << day;
     cout << "/" << year << "\n";
   }

};

int main() {

 date ob1(12, 4, 2003), ob2("10/22/2003");
 ob1.show_date();
 ob2.show_date();
 return 0;

}</source>

12/4/2003
10/22/2003

Overload constructor for different data format

<source lang="cpp">#include<iostream.h>

  1. include<stdio.h>

class date {

 int day,month,year;

public:

 date(char *str);
 date(int m,int d,int y);
 date::date();
 void show();

}; date::date(char *str) {

 scanf(str,"*c*cd",&month,&day,&year);

} date::date(int m,int d,int y) {

 day=d;
 month=m;
 year=y;

} date::date() {

 cout<<"Enter month_day_year:";
 cin>>day;
 cin>>month;
 cin>>year;

} void date::show() {

 cout<<month<<"/"<<day<<"/";
 cout<<year<<"\n";

} main() {

 date sdate("11/1/1999");
 date idate(12,2,1998);
 date indate;
 sdate.show();
 idate.show();
 indate.show();
 return 0;

}</source>

1
Enter month_day_year:2
3
1
16/2009312941/0
12/2/1998
3/2/1

Overload constructor two ways: with initializer and without initializer

<source lang="cpp">#include <iostream>

  1. include <new>

using namespace std; class powers {

 int x;

public:

 powers() {
    x = 0;
    cout << "\nno initializer\n\n";
 }
 powers(int n) {
    x = n;
    cout << "\n\ninitializer:" << x;
 }
 int getx() { return x; }
 void setx(int i) { x = i; }

}; int main() {

 powers ofTwo[] = {1, 2, 4, 8, 16}; // initialized
 powers ofThree[5];                 // uninitialized

}</source>

initializer:1
initializer:2
initializer:4
initializer:8
initializer:16
no initializer

no initializer

no initializer

no initializer

no initializer

Overload the constructor

<source lang="cpp">#include <iostream> using namespace std;

class MyClass { public:

 int x; 
 int y; 

 // Overload the default constructor. 
 MyClass() { x = y = 0; } 

 // Constructor with one parameter. 
 MyClass(int i) { x = y = i; } 

 // Constructor with two parameters. 
 MyClass(int i, int j) { x = i; y = j; } 

};

int main() {

 MyClass t;         // invoke default constructor 
 MyClass t1(5);     // use MyClass(int) 
 MyClass t2(9, 10); // use MyClass(int, int) 

 cout << "t.x: " << t.x << ", t.y: " << t.y << "\n"; 
 cout << "t1.x: " << t1.x << ", t1.y: " << t1.y << "\n"; 
 cout << "t2.x: " << t2.x << ", t2.y: " << t2.y << "\n"; 

 return 0; 

}</source>

t.x: 0, t.y: 0
t1.x: 5, t1.y: 5
t2.x: 9, t2.y: 10

The default constructor for class X is one that takes no arguments;

<source lang="cpp">//If no user-defined constructors exist for a class, //C++ system generates a default constructor.

  1. include <iostream.h>

class Time {

              int hh,mm,ss;
 public:
              //Time(){hh=0;mm=0;ss=0;}
              void Set(int h, int m, int s)   {hh = h; mm = m; ss=s;}
              void Disp();

}; void Time::Disp() {

              cout << "The time is " << hh << ":" << mm << ":" << ss <<endl;

} int main() {

              Time t1;
              t1.Disp();
              t1.Set(2,22,22);                t1.Disp();
              return 0;

}</source>

The time is 2009312941:16:0
The time is 2:22:22

Use constructor to initialize class fields

<source lang="cpp">#include <iostream> using namespace std; class MyClass { public:

 int x;
 MyClass(int i);  // constructor
 ~MyClass();      // destructor

}; MyClass::MyClass(int i) {

   x = i;

} MyClass::~MyClass() {

 cout << "Destructing object whose x value is " << x  <<" \n";

} int main() {

 MyClass ob(5) ;
 cout << ob.x << "\n";
 return 0;

}</source>

5
Destructing object whose x value is 5

Virtual copy constructor

<source lang="cpp">#include <iostream>

class Animal
{
public:
    Animal():itsAge(1) { std::cout << "Animal constructor...\n"; }
    virtual ~Animal() { std::cout << "Animal destructor...\n"; }
    Animal (const Animal & rhs);
    virtual void Speak() const { std::cout << "Animal speak!\n"; }
    virtual Animal* Clone() { return new Animal(*this); } 
    int GetAge()const { return itsAge; }

protected:
    int itsAge;
};

Animal::Animal (const Animal & rhs):itsAge(rhs.GetAge())
{
    std::cout << "Animal Copy Constructor...\n";
}

class Dog : public Animal
{
public:
    Dog() { 
       std::cout << "Dog constructor...\n"; 
    }
    virtual ~Dog() { 
       std::cout << "Dog destructor...\n"; 
    }
    Dog (const Dog & rhs);
    void Speak()const { 
       std::cout << "Woof!\n"; 
    }
    virtual Animal* Clone() { return new Dog(*this); }
};

Dog::Dog(const Dog & rhs): Animal(rhs)
{
    std::cout << "Dog copy constructor...\n";
}

class Cat : public Animal {
public:
    Cat() { 
       std::cout << "Cat constructor...\n"; 
    }
    virtual ~Cat() { 
       std::cout << "Cat destructor...\n"; 
    }
    Cat (const Cat &);
    void Speak()const { 
       std::cout << "Meow!\n"; 
    }
    virtual Animal* Clone() { 
       return new Cat(*this); 
    }
};

Cat::Cat(const Cat & rhs): Animal(rhs)
{
    std::cout << "Cat copy constructor...\n";
}

int main()
{
    Animal *theArray[3];
    Animal* ptr;
    int choice,i;
    theArray[0] = new Dog;
    theArray[1] = new Cat;
    theArray[2] = new Animal;
     
    
    Animal *OtherArray[3];
    for (i=0;i<3;i++)
    {
        theArray[i]->Speak();
        OtherArray[i] = theArray[i]->Clone();
    }
    for (i=0;i<3;i++)
        OtherArray[i]->Speak();
    return 0;
}</source>
Animal constructor...
Dog constructor...
Animal constructor...
Cat constructor...
Animal constructor...
Woof!
Animal Copy Constructor...
Dog copy constructor...
Meow!
Animal Copy Constructor...
Cat copy constructor...
Animal speak!
Animal Copy Constructor...
Woof!
Meow!
Animal speak!