Lecture Notes for Advanced Programming II

25 April 2002 - Wrapping with Classes


Outline


Classes


Classes and Pointers


Pointers in Classes


Constructors and Destructors


Copying and Assignment


Pointer Behavior


Example


$ cat t.cc
struct widget {

  widget(std::string str) : str(str) { 
    std::cerr << "Creating a " << str << " widget.\n"; 
    }
 ~widget() { 
    std::cerr << "Deleting a " << str << " widget.\n";
    }
  widget * clone(void) const { return 0; }

  const std::string str;
  };


int main() {
  handle<widget> w1h = new widget("red");
  if (w1h) {
    handle<widget> w2h = new widget("blue");
    }
  }

$ g++ -o t -ansi -pedantic -Wall t.cc

$ ./t
Creating a red widget.
Creating a blue widget.
Deleting a blue widget.
Deleting a red widget.

$ 

See the complete code.


Another Example

$ cat t.cc
struct widget {
  std::string name;
  std::string type;
  widget * clone(void) const { return 0; }
  };

std::ostream & 
operator << (std::ostream & os, const widget & w) {
  return os << "A " << w.type 
            << " widget named " << w.name;
  }

int
main() {
  handle<widget> wh = new widget();

  wh->name = "joe";
  wh->type = "blue";

  std::cout << *wh << "\n";
  }

$ g++ -o t -ansi -pedantic -Wall t.cc

$ ./t
A blue widget named joe

$ 


A Final Example

$ cat t.cc
struct widget {
  std::string name;
  std::string type;
  };

int
main() {
  handle<widget> wh = new widget();

  wh->name = "joe";
  wh->type = "blue";

  std::cout << *wh << "\n";
  }

$ g++ -o t -ansi -pedantic -Wall t.cc
t.cc: In copy constructor handle<T>::handle(const handle<T>&) 
      [with T = widget]:
t.cc:58:   instantiated from here
t.cc:16: no matching function for call to widget::clone()

$ 


Sharing vs. Copying


Implementation Changes


Sharing Semantics


Copying and Sharing


Example

$ cat t.cc
int
main() {
  handle<widget> w1h = new widget();
  w1h->name = "joe";
  w1h->type = "blue";

  handle<widget> w2h = w1h;
  w2h.clone();
  w2h->type = "green";

  std::cout << "w1h:  " << *w1h << ".\n";
  std::cout << "w2h:  " << *w2h << ".\n";
  }

$ g++ -o t -ansi -pedantic -Wall t.cc

$ ./t
w1h:  A blue widget named joe.
w2h:  A green widget named joe.

$ 

See the complete code.


Points to Remember


This page last modified on 28 April 2002.