Skip to content

Commit

Permalink
Add cast
Browse files Browse the repository at this point in the history
  • Loading branch information
tony-maulaz committed May 12, 2022
1 parent e6546de commit fb931ad
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 1 deletion.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,7 @@
- [allocation.md](https://github.com/tony-maulaz/poo-exercices/blob/main/ex80-allocation.md)

## Ex 90 - Exception
- [exception.md](https://github.com/tony-maulaz/poo-exercices/blob/main/ex90-exception.md)
- [exception.md](https://github.com/tony-maulaz/poo-exercices/blob/main/ex90-exception.md)

## Ex 100 - Cast
- [cast.md](https://github.com/tony-maulaz/poo-exercices/blob/main/ex100-cast.md)
108 changes: 108 additions & 0 deletions ex100-cast.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Cast

## Ex 1
Quel est l'affichage du programme suivant ?

```cpp
#include <iostream>

using namespace std;

struct ClassA {
virtual void show(){ cout << "Hello" << endl; }
};

struct ClassB : public ClassA {
void show(){ cout << "Bonjour" << endl; }
void test(){ cout << "Test" << endl; }
};

void print(ClassA* c){

c->show();

ClassB* pt = dynamic_cast<ClassB*>(c);
if( pt != nullptr ){
pt->test();
}
}

int main()
{
ClassB cb;
print(&cb);

return 0;
}
```


## Ex 2
Modifier la boucle `for`afin d'obtenir l'affichage suivant :
```
A
A
B
A
C
```

```CPP
#include <iostream>

using namespace std;

struct ClassA {
virtual void testA(){ cout << "A" << endl; }
};

struct ClassB : public ClassA {
void testB(){ cout << "B" << endl; }
};

struct ClassC : public ClassA {
void testC(){ cout << "C" << endl; }
};


void print(ClassA* tab[], int size){

for(int i=0; i<size; i++){

}
}

int main()
{
ClassA* tab[3];
tab[0] = new ClassA();
tab[1] = new ClassB();
tab[2] = new ClassC();

print(tab, 3);

return 0;
}
```


# Solution
## Ex 2
```CPP
void print(ClassA* tab[], int size){

for(int i=0; i<size; i++){
tab[i]->testA();
ClassB* cb = dynamic_cast<ClassB*>(tab[i]);
if( cb != nullptr ){
cb->testB();
}
ClassC* cc = dynamic_cast<ClassC*>(tab[i]);
if( cc != nullptr ){
cc->testC();
}
}
}
```

0 comments on commit fb931ad

Please sign in to comment.