Object Relationships
Object Relationships

The is-a relationship - Client's view

Works in only one direction

Every Sub object object is also a Super one

Supper object is not a Sub

void foo1(const Super& s);
void foo2(const Sub& s);
Super super;
Sub sub;
foo1(super);//okay
foo1(sub);//okay
foo2(super);//Not okay
foo2(sub); //Okay
				
Object Relationships

The is-a relationship - Client's view

class Super{
public:
	virtual void m1();
};
class Sub : public Super{
	virtual void m2();	
};
				
Super *p = new Super();
p->m1(); //Okay
p = new Sub();
p->m1(); //Okay
p->m2(); //Not Okay
((Sub*)p)->m2(); //Okay
				
Object Relationships

The is-a relationship - Sub-class's view

The Sub class augments the Super class by adding additional methods

The Sub class may override the Super class

The subclass can use all the public and protected members of a superclass

Object Relationships

Polymorphism

The is-a relationhip: a client's view of overridden methods(1)

class Super{
public:
	virtual void method1();
};
class Sub : public Super{
	virtual void method1();	
};
				
Super super;
super.method1();//Super::method1()
Sub sub;
sub.method1();	//Sub::method1()
Super& ref = super;
ref.method1(); //Super::method1();
ref = sub;
ref.method1();	//Sub::method1();
Super* ptr = &super;
ptr->method1();	//Super::method1();
ptr = ⊂
ptr->method1();//Sub::method1();
				
Object Relationships

object slicing

The is-a relationhip: a client's view of overridden methods(2)

class Super{
public:
	virtual void method1();	
};
class Sub : public Super{
public:
	virtual void method1();
};
				
Sub sub;
Super super = sub;
super.method1(); //Super::method();
				
Object Relationships

The has-a relationship

Object Relationships

Implementing the has-a relationship

An object A has an object B

class B{	
};
class A{
	B b;
};
				
class B{	
};
class A{
	B* b;
};
				
class B{	
};
class A{
	B& b;
};
				
Object Relationships

Implementing the has-a relationship

An object A has an object B

Strong containment (composition)

class B{	
};
class A{
	B b;
};

				
A anObject;
				
Object Relationships

Implementing the has-a relationship

An object A has an object B

Weak containment (aggregation)

class B{	
};
class A{
	B& b;
public:
	A(const &B rb):b(rb){}
};

				
B b;
A a1(b);
A a2(b);
				
Object Relationships

Implementing the has-a relationship

An object A has an object B

Weak containment

class B{
};
class A{
	B* b;
public:
	A(B* pb):b(pb){}
};
				

Strong containment

class B{
};
class A{
	B* b;
public:
	A(){
		b = new B();
	}
	~A(){delete b;}
};
				
Object Relationships

Implementing the has-a relationship

An object A has an object B

Weak containment(aggregation)

class B{	
};
class A{
	B* b;
public:
	A(B* pb):b(pb){}
};
				
Usage
B b;
A a1(&b);
A a2(&b);
				
Object Relationships

Implementing the has-a relationship

An object A has an object B

Strong containment

class B{
};
class A{
	B* b;
public:
	A(){
		b = new B();
	}
	~B(){ delete b;}
};
				
Usage
A a;