Object-Oriented Programming Objects Methods

silkthrilledΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 8 μήνες)

74 εμφανίσεις

CSC 4101: Programming Languages 1
1
Object-Oriented Programming
Textbook Chapter 9
Objects
struct S {
int x;
float y;
};
S a;
a.x = 42;
a.y = 3.14;
S * p = &a;
S * q = new S;
int i = p->x;
int j = q->x;
a: x = 42
y = 3.14
p:
q:
2
Methods
struct S {
int x;
float y;
int getX() { return x; }
};
S * p = new S;
p->x = 42;
p->y = 3.14;
int i = p->getX();
3
CSC 4101: Programming Languages 2
Constructors
struct S {
int x;
float y;
S(int a, float b) { x = a; y = b; }
int getX() { return x; }
};
S * p = new S(42, 3.14);
int i = p->getX();
4
Visibility Specifiers
struct S {
private:
int x;
float y;
public:
S(int a, float b) { x = a; y = b; }
int getX() { return x; }
};
S * p = new S(42, 3.14);
int i = p->getX();
int j = p->x;
5
struct vs. class
struct S {
private:=
...
};
class S {
public:=
...
};
class S {
...
};
struct S {
...
};
6
CSC 4101: Programming Languages 3
Inheritance
class C {
int x;
public:
C(int a) { x = a; }
int getX() { return x; }
};
class D : public C {
int y;
public:
D(int a,int b) :C(a) {y=b;}
int getY() { return y; }
};
C * p = new C(42);
D * q = new D(42, 3);
p:x = 42
q:x = 42
y = 3
7
Subtyping
class D : public C { ... };
C * q = new D(42, 3);
q:x = 42 C part
y = 3
A D object can be used wherever a C object is expected.
8
Virtual Methods
class C {
protected:
int x;
public:
C(int a) { x = a; }
virtual void print() { cout << x; }
};
class D : public C {
int y;
public:
D(int a, int b) : C(a) { y = b; }
virtual void print() { cout << '(' << x << ", " << y << ')'; }
};
C * p = new D(42, 3);
p->print();
9
CSC 4101: Programming Languages 4
Virtual Methods

Conceptually
p:x = 42
print D::print
y = 3
10
Virtual Methods

Actual Implementation
p:x = 42 C_D_vtable:
_vtbl
y = 3 D::print
p->print()
is translated to
((*(p->_vtbl))[1])(p)
11