Skip to content

Commit

Permalink
Merge pull request #17 from kenluobo/add_virtual_method_test_case
Browse files Browse the repository at this point in the history
Add virtual method test case
  • Loading branch information
kenluobo authored Nov 23, 2024
2 parents ce976f0 + b6f6687 commit 6473948
Showing 1 changed file with 84 additions and 0 deletions.
84 changes: 84 additions & 0 deletions cplusplus/stl/11_virtual_method.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#include "utils/test.hpp"
#include <cstdint>
#include <string>

//==================================================================
enum class AnimalCategory : std::uint8_t {
LandAnimal = 0,
WaterAnimal,
Amphibian
};

static std::string convertAnimalCategoryToString(AnimalCategory AC) {
switch (AC) {
case AnimalCategory::LandAnimal:
return "LandAnimal";
case AnimalCategory::WaterAnimal:
return "WaterAnimal";
case AnimalCategory::Amphibian:
return "Amphibian";
}
}

//==================================================================
class Animal {
public:
virtual AnimalCategory getCategory() = 0;
virtual std::string getCategoryAsString() = 0;

private:
AnimalCategory AC;
};

//==================================================================
class Human : public Animal {
public:
virtual AnimalCategory getCategory() { return AC; }
virtual std::string getCategoryAsString() {
return convertAnimalCategoryToString(AC);
}
virtual ~Human() = default;

private:
AnimalCategory AC = AnimalCategory::LandAnimal;
};

class Employee : public Human {
public:
virtual ~Employee() = default;
};

//==================================================================
class Fish : public Animal {
public:
virtual AnimalCategory getCategory() { return AC; }
virtual std::string getCategoryAsString() {
return convertAnimalCategoryToString(AC);
}

private:
AnimalCategory AC = AnimalCategory::WaterAnimal;
};

//==================================================================
void test_virtual_method() {
// todo
Human h;
out("Human ", h.getCategoryAsString());

Employee e;
out("Employee ", e.getCategoryAsString());

Fish f;
out("Fish ", f.getCategoryAsString());

Employee *p_e = &e;
out("Employee Pointer ", p_e->getCategoryAsString());
out("Human Pointer ", static_cast<Human *>(p_e)->getCategoryAsString());
}

//==================================================================
void test() { TEST(test_virtual_method); }

//==================================================================
int main() { test(); }

0 comments on commit 6473948

Please sign in to comment.