Week 5 Lecture Summary for CSC 309

These notes are not intended to be complete. They serve as an outline to the class and as a supplement to the text.

Constructors

Example

class Complex
{
   private:
      double real;
      double imag;
   
   public:
      void set(double r, double i) {
          real = r;
          imag = i;
      }    
		:
		:
};

int main(){

    Complex c1,c2,c3;   // okay, default is called
    Complex nums [30];  // okay, default is called 30 times.
}

Note: if you define at least one constructor the compiler will not generate the default constructor.

Example

class Complex 
{
    private:
        double real;
        double imag;
    public:
        Complex (double r, double i) {
            real = r;
            imag = i;
        }
        :
};

int main() {

    Complex c1,c2,c3;   // error default taken away.
    Complex nums [10];  // error default taken away.

}

The default or no-arg constructor is implicitly called in certain situations.


Constructor Inializer List


The Copy Constructor


Convert Constructor


The Assignment Operator


The Destructor

The copy constructor, the assignment operator and the destructor are called the Big Three. They should be defined whenever your class has members that are dynamically allocated.


The this Pointer


Pointers to Objects


A Class With Pointer Members

class Name
{
    private:
        char *first;        
        char *last;      
    
    public:
        Name();       
        Name(char *f, char *l);
        Name(const Name & n);
        ~Name();
        const Name & operator= (const Name &rhs);
        void println(ostream& out) const;
}; 

Name::~Name(){    
    delete [] first;    
    delete [] last;
}
Name::Name()
{
    first = new char[1];
    first[0] = '\0';   
    last = new char[1];
    last[0] = '\0';
}

Name::Name(char *f, char *l)
{
    if(NULL == f){
        f = "NONE";
    }
    if(NULL == l){
        l = "NONE";
    }
    first = new char[strlen(f) + 1];
    strcpy(first, f);  
    last = new char[strlen(l) + 1];
    strcpy(last,l);
}
Name::Name(const Name & n) 
{
    first = new char[strlen(n.first) + 1];
    strcpy(first, n.first);  
    last = new char[strlen(n.last) + 1];
    strcpy(last,n.last);    
}  

const Name & Name::operator= (const Name& rhs)
{    
	if(this != &rhs){
        if(strlen(first) != strlen(rhs.first)){
            delete [] first;  
            first = new char [strlen(rhs.first) + 1];          
        }
        if( strlen(last) != strlen(rhs.last)) {
            delete [] last;
            last = new char [strlen(rhs.last) + 1];
        }
        strcpy(first, rhs.first);
        strcpy(last,  rhs.last); 
    }
    return *this;
}

void Name::println(ostream & out) const{
        out << last << ", " << first << endl;    
}