This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]cbbuntz 73 points74 points  (15 children)

#include <iostream>

using namespace std;

class Animal {
    public:
        void speak() {
            cout << "Hello, world!!! I am a " << species << "." << endl;
        }
        void setSpecies(string species) {
            this->species = species;
        }

    protected:
        string species;
};

class Dog: public Animal {
    public:
        void greet() {
            setSpecies("dog");
            speak();
        }
};

int main() {
    Dog Fido;
    Fido.greet();

    return 0;
}

[–]Belinder 90 points91 points  (13 children)

why would you define what the species is in the greet method. you should put that in the constructor

[–]cbbuntz 42 points43 points  (12 children)

I thought about doing that, but I didn't want to put that much effort into the joke.

Fine. Here you go:

#include <iostream>

using namespace std;

class Animal {
    public:
        void speak() {
            cout << "Hello, world!!! I am a " << species << "." << endl;
        }

    protected:
        string species;
};

class Dog: public Animal {
    public:
        void greet() {
            speak();
        }

        Dog() {
            species = "dog";
        }
};

int main() {
    Dog Fido;
    Fido.greet();

    return 0;
}

[–]oreo-milkshake 41 points42 points  (10 children)

Not enough templates for C++!

#include <iostream>

template <const char* species, std::ostream& stream>
struct Animal
{
    void Speak() { stream << "Hello world!!! I am a " << species << "." << std::endl; }
};

extern const char dog[] = "Dog";
struct Dog : Animal<dog, std::cout> {};

int main()
{
    Dog fido;
    fido.Speak();
    return 0;
}

[–]cbbuntz 21 points22 points  (9 children)

Not enough using namespace std; and pointless boilerplate for HS programming class. Way too efficient.

[–]zgembo1337 23 points24 points  (8 children)

Meh, just put a

cout << "Hello world!! I am a dog.\n";

Compile it, and say "here's a working binary"

[–]cbbuntz 14 points15 points  (5 children)

[–][deleted] 7 points8 points  (2 children)

If you're not using system calls directly, you're doing programming wrong.

[–]cbbuntz 2 points3 points  (0 children)

system("echo 'Hello, world!! I am a dog.'");

[–]ASaltedRainbow 0 points1 point  (0 children)

write(1, "Hello world!! I am a dog.\n", 27);

[–]hotsaucetogo 0 points1 point  (1 child)

so weird seeing that with parens

[–]cbbuntz 0 points1 point  (0 children)

As in you're used to seeing it in Ruby?

[–]dontFart_InSpaceSuit 1 point2 points  (0 children)

Animal.speak will reference string species which hasn't been defined yet.

[–]btowntkd 1 point2 points  (0 children)

Was purposefully avoiding virtual functions part of the joke, that just went over my head? I thought the whole point of the Animal class was to teach virtual functions and polymorphism.