Skip to content

Commit

Permalink
add single inheritance
Browse files Browse the repository at this point in the history
  • Loading branch information
cagix committed Jan 11, 2025
1 parent a4739a1 commit 7bb9ece
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion homework/src/cpp/Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
all: vars refs expr ifthenelse while func class
all: vars refs expr ifthenelse while func class inheritance

%: %.cpp driver.h
g++ -include driver.h $<
Expand Down
43 changes: 43 additions & 0 deletions homework/src/cpp/inheritance.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class A {
public: // es reicht, wenn alles public ist (hier nur, damit das Beispiel mit g++ kompiliert)
A(int x) { aval = x; }

void foo() { print_char('A'); print_char('f'); print_int(aval); }

int aval;
};

class B : public A {
public: // es reicht, wenn alles public ist (hier nur, damit das Beispiel mit g++ kompiliert)
// C'tor muss Basisklasse initialisieren
B(int x) : A(x+3) { bval = x; }

// überschriebene Methode aus A
void foo() { print_char('B'); print_char('f'); print_int(aval); print_int(bval); }

// eigene Methode
void bar() { print_char('B'); print_char('b'); print_int(aval); print_int(bval); }

int bval;
};


int main() {
// Vererbung: Initialisierung Basisklasse; Überschreiben von Methoden
A x(2);
B y(7);

x.foo(); // A, f, 2
y.foo(); // B, f, 10, 7
y.bar(); // B, b, 10, 7

x.aval = 8;
y.bval = 4;

x.foo(); // A, f, 8
y.foo(); // B, f, 10, 4
y.bar(); // B, b, 10, 4


return 0;
}

0 comments on commit 7bb9ece

Please sign in to comment.