C++ example code - Eliens. Chapter 2
Slide 2-4: Encapsulation
counter c; // calls default constructor counter() { n=0;}
c++;
cout << c.value();
Slide 2-5: Constructors and destructors
counter c("ctr-1"); c++;
// calls
//counter(char* s, int v=0): n(v) { init(s);}
cout<< c.name() << "=" << c.value();
Slide 2-6: Protection
counter c("ctr-2"); c++;
c.name()[4] = ‘1’;
// const char* name() const { return id;}
cout << c.name() << "=" << c.value();
//Results in compile time error due to first const
Slide 2-7: Type conversion
void fun( counter& c) {
cout << (char* ) c << " = " << (int) c;
// operator char * () {return id; }
}
// constructor converts char *
fun("ctr-3"); // works creating a counter
// but new operator conversions
// must be made unambiguous or it is possibly dangerous.
Slide 2-8: Overloading and friends
counter c("ctr-4"); c++;
if (c < 2)
cout << c.name() << "=" << c.value();
// friend int operator<(counter&, int);
Slide 2-9: Inheritance
class shape {
public:
shape( int x= 0, int y = 0) : _x(x), _y(y) {}
void move(int x, int y) { _x +=x; _y +=y;}
virtual void draw()= 0;
// pure virtual function hence abstract class
protected:
int _x, _y;
};
shape s: // compiler error abstract class
Slide 2-10: Concrete shapes
circle c(1,1,2); rectangle r(2,2,1,1);
c.draw(); r.draw(); //overriding of absract draw()
Slide 2-13 Virtual base Classes
class student : virtual public person {...}
// to ensure that student_assistant contains only one //copy of person class
person* p=new student_assistant(20,6777,300);
// otherwise would not work as ambiguity on which person meant
Slide 2-18: A string class
string s1("hello"), s2("world); // conversion, creation
cout << (char *) s1 << (char *) s2;
// explicit cast
// could have overloaded output operator(<<) for string
string s3(s1); string s4 = s2;
// two strings created
// based on copies of previous strings
// copy constructor called both times
cout << (char*) s3 << (char*) s4;
string s5; s5 = s3 + ‘ ‘ + s4;
//assignment operator used to store results of
// concatenation
cout << (char*)s5;
Slide 2-27: Iterator class
void main() {
list<int> lst;
lst.insert(1); lst.insert(2);
iter<int> it = lst; // get iterator
int* p = 0; // start
while ( p = it()) {
cout << "item" << *p << endl;
}
}
Slide 2-29: Benefits and pitfalls of C++
//because arrays are treated like pointers
typedef int intarray[10];
intarray a, *p;
p = &a; // warning illegal pointer combination
// whereas
typedef int Int;
Int i, *pi;
pin = &i; // accepted
Slide 2-34: Virtual destructors
A* a = new B; delete a; //ABBA
B* b = new B; delete b; //ABBA
Slide 2-35: Multiple inheritance
//without virtual inheritance
D* a = new D(); delete a; //ABACDDCABA
//with virtual
A* a - new D(); delete a; //ABCDDCBA