What does "data abstraction" exactly mean? - c++

What does data abstraction refer to?
Please provide real life examples alongwith.

Abstraction has two parts:
Hide details that don't matter from a certain point of view
Identify details that do matter from a certain point of view and consider items to be of the the same class if they possess those details.
For example, if I am designing a program to deal with inventory, I would like to be able to find out how many items of a certain type the system has in stock. From the perspective of the interface system, I don't care if I am getting this information from a database, a csv file, a remote repository via a SOAP interface or punch cards. I just care that I can can say widget.get_items_in_stock() and know that it will return an integer.
If I later decide that I want to record that number in some other way, the person designing the interface doesn't need to know, care or worry about it as long as widget still has the get_items_in_stock() method. Like wise, the interface doesn't need to care if I subclass the widget class and add a get_square_root_of_items_in_stock() method. I can pass an instance of the new class to it just as well.
So in this example, we've hidden the details of how the data is acquired and decided that anything with a get_items_in_stock() method is an instance of the same class (or a subclass thereof) for certain purposes.

Data abstraction is any device that allows you to treat data as humans encounter it rather than as it is stored on machine.
At the lowest level, all primitive data types are abstractions -- as programmers, we don't usually have to deal with data at the bit level (which is how it is ultimately stored) but as integers, floating point numbers, characters, etc.
We then add layers onto that abstraction -- maybe two integers represents a Point, or we and enumerations to represent the months of the year, days of the week, etc.
With each abstraction layer, we move further from the machine and (hopefully) closer to human understanding of the data. This can extract a performance penalty -- it may not always be the case that points can be most efficiently represented by two integers. This is compensated for by the shorter development (and maintenance) time when abstractions are used.

The technique of creating new data type that is well suited to an application to be programmed is known as data abstraction.

Abstraction means providing only essential information to the outside world and hiding their background details..examp. In ur Computer u can see only monitor, keyboard nd mouse..u don't know anything about internal wiring this is abstraction.

Data abstraction seems to be explained as breaking data down as far as you can get it. food would be the abstraction of apple, orange, pizza. animal would be the abstraction of cat, cow, pig. A food object would be something like this pseudo code:
class food{
name;
calories;
weight;
public eat(name);
}
all foods have a name, calorie amount, and a weight. That's pretty abstract.
You could then make objects that inherit, which would be a bit less abstract.
class pizza inherits food{
toppings;
say_toppings();
}
pizza now has toppings, but it inherits name, calories, and weight from food.
basically abstraction has been explained as getting to the lowest level of each item and making classes that extend from them. It makes your code more reusable too... If you've bade your base class of food well enough, and included everything abstract about it anyone working in the food industry could use your class.

Abstraction is hiding the skeleton from the human body. The skin does a great way of containing it. (See how abstract I'm being there? Pun intended. I digress...)
If I have a water bottle, then I'm able to drink from it by opening the lid, twisting it until it pops off.
bool lid_open = false;
void open_water_bottle_by_twisting() { lid_open = true; }
But water bottles are containers. Containers hold liquids until they become open and they are able to be drunk from (assuming the liquid is drinkable).
class Container
{
bool lid_open = false;
protected:
Container() {}
void open_by_twisting()
{
lid_open = true;
}
public:
virtual ~Container();
};
class WaterBottle : public Container
{
WaterBottle() : Container() {}
public:
~WaterBottle();
};
However, not all containers are opened the same way. Some containers, such as the water bottle, have lids that can be twisted off. Others don't have lids, such as exercise bottles - those contain bendy straws that can be bent down for storage or up for drinking.
class Container
{
bool lid_open;
bool straw_open;
protected:
void TurnLid() { lid_open = true; }
void BendStraw() { straw_open = true; }
Container() : lid_open(false), straw_open(false){}
public:
virtual void open() = 0;
virtual ~Container();
};
class WaterBottle : public Container
{
public:
WaterBottle() : Container() {}
void open()
{
TurnLid();
}
~WaterBottle();
};
class ExerciseBottle : public Container
{
public:
ExerciseBottle() : Container() {}
void open()
{
BendStraw();
}
~ExerciseBottle();
};
But the client doesn't know what ExerciseBottle's implementation of ExerciseBottle's open() is. It calls BendStraw(), which then sets straw_open to true. But ExerciseBottle simply calls one function to do all of this work. The client doesn't have to perform several actions that are used in the implementation of open(). The case goes similarly for WaterBottle. And that's what abstraction is: letting the client know that the back-end will do all of the work for it. When the term "separating implementation from interface" is used, this is what is meant.

Is the complex system that uses data details which are easy to interact or encounter with humans, which differ from the way computer system stores such as in binary number system.
Answered by Neema, Rohan and Upendo (The programmers)

The technique of limiting the data attributes according to given scenario for development of software and removing all irrelevant attributes.This makes software development simpler.

Let's take one real life example of a TV which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players BUT you do not know it's internal detail that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen.

It refers to the act of representing essential feature without including the background detail or the explanation

It is difficult to find day to day life example of DATA abstraction. However, any data types in programming language, tables and view in DBMS, data structures like LinkedList, List, Queue, Stack are data abstractions. These abstractions provide you the way to access the data in particular manner.
This article may help you understand data abstraction and control abstraction in depth. It also has some of the real life examples of control and data abstractions.

Abstraction rrefers to the act of representing essential features without including the background detail or explanation.

Simply Data Abstraction is nothing but the hiding unnecessary datails from user.
Example:Person simply just wants to make a call, he just select or dial no. and click on call button this info. is enough for him.He dont want to know about how connection is made and whatever process behind making call or how voice is transferred.

I know this question was asked long time ago. But still like to share one real life example which might help others to understand concept of abstraction very easily.
A real-world analogy of abstraction might work like this: You (the object) are arranging to meet a blind date and are deciding what to tell them so that they can recognize you in the restaurant. You decide to include the information about where you will be located, your height, hair color, and the color of your jacket. This is all data that will help the procedure (your date finding you) work smoothly. You should include all that information. On the other hand, there are a lot of bits of information about you that aren't relevant to this situation: your social security number, your favorite football players all are irrelevant to this particular situation because they won't help your date to find you.

Data Abstraction:
It is used to provide the necessary information to the user and hide the unnecessary information from the user. It is called data abstraction.
It will hide your business logic from outside the world.
Technical Example: Console.WriteLine();
Non Technical Example: TV remote, Car Remote.
More Detail: Data Abstraction with real-time example

data hiding deals the security features of oops. according to this property private data member of a class is accessible or visual only inside the class not outside the class.

Related

How to avoid using dynamic_cast, when implementing external actions?

dynamic_cast is pure evil. Everybody knows it. Only noobs use dynamic_cast. :)
That's what I read about dynamic_cast. Many topics on stackoverflow say "use virtual functions in this case".
I've got some interfaces that reflect capabilities of objects. Let's say:
class IRotatable
{
virtual void set_absolute_angle(float radians) =0;
virtual void rotate_by(float radians) =0;
};
class IMovable
{
virtual void set_position(Position) =0;
};
and a base for a set of classes that may implement them:
class Object
{
virtual ~Object() {}
};
In GUI layer I would like to enable/disable or show/hide buttons depending on which features are implemented by the object selected by the user:
Object *selected_object;
I would do it in such a way (simplified):
button_that_rotates.enabled = (dynamic_cast<IRotatable*>(selected_object) != nullptr);
(...)
void execute_rotation(float angle)
{
if(auto rotatable = dynamic_cast<IRotatable*>(selected_object))
{
rotatable->rotate_by(angle);
}
}
but as other (more experienced ones) say, it is obvious evidence of bad design.
What would be a good design in this case?
And no, I don't want a bunch of virtual functions in my Object. I would like to be able to add new interface and new classes that implement it (and new buttons) without touching Object.
Also virtual function like get_buttons in by Object doesn't seem good for me. My Object knows completely nothing about GUI, buttons and such things.
A function like get_type that returns some enum could also solve a problem, but I don't see why self-implemented substitute of RTTI should be better than the native one (ok, it would be faster, but it doesn't matter in this case).
You've already hit the nail on the head: you're trying to get type information from an "opaque" Object* type. Using dynamic_cast is just a hack to get there. Arguably your problem is actually that C++ doesn't have what you want: good type information. But here's some thoughts.
First, if you're going to a lot of this sort of thing, you may find that you are actually shifting away from typical inheritance and your program may be better suited to a component based design pattern, as is more common in video games. There you often have a somewhat opaque GameObject at the root and want to know what "components" it has. Unity does this sort of thing and they have nice editor windows based on components attached to the GameObject; but C# also has nice type info.
Second, some other part of the might know about the concrete type of the object and can help build your visual display, causing the Object* to no longer be a bottleneck.
Third, if you do go with something like the option you're talking about, I think you will find having type id of some sort vs. the use of dynamic_cast to be more helpful, since you can then build tables to look up types to say, visual builders.
Also, you were wondering why a self-rolled type info vs. RTTI? If you are quite concerned about performance, RTTI is on for all types and that means everything could take a hit; the self-rolled option allows for opt-in (at the cost of complexity). Additionally you won't need to push this onto others if you're writing a library pulled in via source, etc.

Accessing subclass functions of member of collection of parent class objects

(Refer Update #1 for a concise version of the question.)
We have an (abstract) class named Games that has subclasses, say BasketBall and Hockey (and probably many more to come later).
Another class GameSchedule, must contain a collection GamesCollection of various Games objects. The issue is that we would, at times, like to iterate only through the BasketBall objects of GamesCollection and call functions that are specific to it (and not mentioned in the Games class).
That is, GameSchedule deals with a number of objects that broadly belong to Games class, in the sense that they do have common functions that are being accessed; at the same time, there is more granularity at which they are to be handled.
We would like to come up with a design that avoids unsafe downcasting, and is extensible in the sense that creating many subclasses under Games or any of its existing subclasses must not necessitate the addition of too much code to handle this requirement.
Examples:
A clumsy solution that I came up with, that doesn't do any downcasting at all, is to have dummy functions in the Game class for every subclass specific function that has to be called from GameSchedule. These dummy functions will have an overriding implementation in the appropriate subclasses which actually require its implementation.
We could explicitly maintain different containers for various subclasses of Games instead of a single container. But this would require a lot of extra code in GameSchedule, when the number of subclasses grow. Especially if we need to iterate through all the Games objects.
Is there a neat way of doing this?
Note: the code is written in C++
Update# 1: I realized that the question can be put in a much simpler way. Is it possible to have a container class for any object belonging to a hierarchy of classes? Moreover, this container class must have the ability to pick elements belonging to (or derive from) a particular class from the hierarchy and return an appropriate list.
In the context of the above problem, the container class must have functions like GetCricketGames, GetTestCricketGames, GetBaseballGame etc.,
This is exactly one of the problems that The "Tell, Don't Ask" principle was created for.
You're describing an object that holds onto references to other objects, and wants to ask them what type of object they are before telling them what they need to do. From the article linked above:
The problem is that, as the caller, you should not be making decisions based on the state of the called object that result in you then changing the state of the object. The logic you are implementing is probably the called object’s responsibility, not yours. For you to make decisions outside the object violates its encapsulation.
If you break the rules of encapsulation, you not only introduce the runtime risks incurred by rampant downcasts, but also make your system significantly less maintainable by making it easier for components to become tightly coupled.
Now that that's out there, let's look at how the "Tell, Don't Ask" could be applied to your design problem.
Let's go through your stated constraints (in no particular order):
GameSchedule needs to iterate over all games, performing general operations
GameSchedule needs to iterate over a subset of all games (e.g., Basketball), to perform type-specific operations
No downcasts
Must easily accommodate new Game subclasses
The first step to following the "Tell, Don't Ask" principle is identifying the actions that will take place in the system. This lets us take a step back and evaluate what the system should be doing, without getting bogged down into the details of how it should be doing it.
You made the following comment in #MarkB's answer:
If there's a TestCricket class inheriting from Cricket, and it has many specific attributes concerning the timings of the various innings of the match, and we would like to initialize the values of all TestCricket objects' timing attributes to some preset value, I need a loop that picks all TestCricket objects and calls some function like setInningTimings(int inning_index, Time_Object t)
In this case, the action is: "Initialize the inning timings of all TestCricket games to a preset value."
This is problematic, because the code that wants to perform this initialization is unable to differentiate between TestCricket games, and other games (e.g., Basketball). But maybe it doesn't need to...
Most games have some element of time: Basketball games have time-limited periods, while Baseball games have (basically) innings with basically unlimited time. Each type of game could have its own completely unique configuration. This is not something we want to offload onto a single class.
Instead of asking each game what type of Game it is, and then telling it how to initialize, consider how things would work if the GameSchedule simply told each Game object to initialize. This delegates the responsibility of the initialization to the subclass of Game - the class with literally the most knowledge of what type of game it is.
This can feel really weird at first, because the GameSchedule object is relinquishing control to another object. This is an example of the Hollywood Principle. It's a completely different way of solving problems than the approach most developers initially learn.
This approach deals with the constraints in the following ways:
GameSchedule can iterate over a list of Games without any problem
GameSchedule no longer needs to know the subtypes of its Games
No downcasting is necessary, because the subclasses themselves are handling the subclass-specific logic
When a new subclass is added, no logic needs to be changed anywhere - the subclass itself implements the necessary details (e.g., an InitializeTiming() method).
Edit: Here's an example, as a proof-of-concept.
struct Game
{
std::string m_name;
Game(std::string name)
: m_name(name)
{
}
virtual void Start() = 0;
virtual void InitializeTiming() = 0;
};
// A class to demonstrate a collaborating object
struct PeriodLengthProvider
{
int GetPeriodLength();
}
struct Basketball : Game
{
int m_period_length;
PeriodLengthProvider* m_period_length_provider;
Basketball(PeriodLengthProvider* period_length_provider)
: Game("Basketball")
, m_period_length_provider(period_length_provider)
{
}
void Start() override;
void InitializeTiming() override
{
m_period_length = m_time_provider->GetPeriodLength();
}
};
struct Baseball : Game
{
int m_number_of_innings;
Baseball() : Game("Baseball") { }
void Start() override;
void InitializeTiming() override
{
m_number_of_innings = 9;
}
}
struct GameSchedule
{
std::vector<Game*> m_games;
GameSchedule(std::vector<Game*> games)
: m_games(games)
{
}
void StartGames()
{
for(auto& game : m_games)
{
game->InitializeTiming();
game->Start();
}
}
};
You've already identified the first two options that came to my mind: Make the base class have the methods in question, or maintain separate containers for each game type.
The fact that you don't feel these are appropriate leads me to believe that the "abstract" interface you provide in the Game base class may be far too concrete. I suspect that what you need to do is step back and look at the base interface.
You haven't given any concrete example to help, so I'm going to make one up. Let's say your basketball class has a NextQuarter method and hockey has NextPeriod. Instead, add to the base class a NextGameSegment method, or something that abstracts away the game-specific details. All the game-specific implementation details should be hidden in the child class with only a game-general interface needed by the schedule class.
C# supports reflections and by using the "is" keyword or GetType() member function you could do these easily. If you are writing your code in unmanaged C++, I think the best way to do this is add a GetType() method in your base class (Games?). Which in its turn would return an enum, containing all the classes that derive from it (so you would have to create an enum too) for that. That way you can safely determine the type you are dealing with only through the base type. Below is an example:
enum class GameTypes { Game, Basketball, Football, Hockey };
class Game
{
public:
virtual GameTypes GetType() { return GameTypes::Game; }
}
class BasketBall : public Game
{
public:
GameTypes GetType() { return GameTypes::Basketball; }
}
and you do this for the remaining games (e.g. Football, Hockey). Then you keep a container of Game objects only. As you get the Game object, you call its GetType() method and effectively determine its type.
You're trying to have it all, and you can't do that. :) Either you need to do a downcast, or you'll need to utilize something like the visitor pattern that would then require you to do work every time you create a new implementation of Game. Or you can fundamentally redesign things to eliminate the need to pick the individual Basketballs out of a collection of Games.
And FWIW: downcasting may be ugly, but it's not unsafe as long as you use pointers and check for null:
for(Game* game : allGames)
{
Basketball* bball = dynamic_cast<Basketball*>(game);
if(bball != nullptr)
bball->SetupCourt();
}
I'd use the strategy pattern here.
Each game type has its own scheduling strategy which derives from the common strategy used by your game schedule class and decouples the dependency between the specific game and game schedule.

Examples of why declaring data in a class as private is important?

I understand that only the class can access the data so therefore it is "safer" and what not but I don't really understand why it is such a big deal. Maybe it is because I haven't made any programs complex enough where data could accidentally be changed but it just a bit confusing when learning classes and being told that making things private is important because it is "safer" when the only time I have changed data in a program is when I have explicitly meant to. Could anyone provide some examples where data would have been unintentionally changed had that data not been private?
Depends what you mean by "unintentional changes". All code is written by someone so if he is changing a member variable of a class then the change is intentional (at least from his side). However the implementor of the class might not have expected this and it can break the functionality.
Imagine a very simple stack:
class Stack
{
public:
int Items[10];
int CurrentItemIndex;
}
Now CurrentItemIndex points to the index which represents the current item on top of the stack. If someone goes ahead and changes it then your stack is corrupted. Similarly someone can just write stuff into Items. If something is public then it is usually a sign that it is intended for public usage.
Also making members private provides encapsulation of the implementation details. Imagine someone iterates over stack on the above implementation by examining Items. Then it will break all code if the implementation of the stack gets changed to be a linked list to allow arbitrary number of items. In the end the maintenance will kill you.
The public interface of a class should always be as stable as possible because that's what people will be using. You do not want to touch x lines of code using a class just because you changed some little detail.
The moment you start collaborating with other people on code, you'll appreciate the clarity and security of keeping your privates private.
Say you've designed a class that rotates an image. The constructor takes an image object, and there's a "rotate" method that will rotate the image the requested number of degrees and return it.
During rotation, you keep member variables with the state of the image, say for example a map of the pixels in the image itself.
Your colleagues begin to use the class, and you're responsible for keeping it working. After a few months, someone points out to you a technique that performs the manipulations more efficiently without keeping a map of the pixels.
Did you minimize your exposed interface by keeping your privates private?
If you did, you can swap out the internal implementation to use on the other technique, and the people who've been depending on your code won't need to make any changes.
If you didn't, you have no idea what bits of your internal state your colleagues are depending on, and you can't safely make any changes without contacting all of your colleagues and potentially asking them to change their code, or changing their code for them.
Is this a problem when you're working alone? Maybe not. But it is a problem when you've got an employer, or when you want to open-source that cool new library you're so proud of.
When you make a library that other people use, you want to show the most basic sub-set of your code possible to allow external code to interface with it. This is called information hiding. It would cause more issues if other developers were allowed to modify any field they wanted, perhaps in an attempt of performing some task. An attempt that would cause unspecified program behaviour.
Generally you want to hide "data" (make vars private) so when people that aren't familiar with the class don't access data directly. Instead if they use Public modifiers to access and change that data.
Eg. accessing name via public setter could check for any problems and also make first character upper case
Accessing data directly will not do those checks and possible changes.
You don't want someone to suddenly fiddle with your internals, no? So do C++'s classes.
The problem is, if anyone can suddenly change the state of a variable that is yours, your class will screw up. It's as if someone suddenly fills your gut with something you don't want. Or exchanges your lung for someone elses.
Let's say you have a BankAccount class where you store a person's NIP and cash amount. Let's put all the fields public and see what could go wrong:
class BankAccount
{
public:
std::string NIP;
int cash;
};
Now, let's pretend that you leave it this way and use it throughout your program. Later on, you find a nasty bug caused by a negative amount of cash (whether it is from calculations or simply an accident). So you spend a couple of hours finding where that negative amount came from and fix it.
You don't want this to happen again, so you decide to put the cash amount private and perform checks before setting the cash amount to avoid any other bugs like the previous one. So you go like this:
class BankAccount
{
public:
int getCash() const { return cash; }
void setCash(int amount)
{
if (amount >= 0)
cash = amount;
else
throw std::runtime_exception("Cash amount is negative.");
}
private:
int cash;
}
Now what? You have to find all the cash references and replace them. A quick and dirty Find and Replace won't fix it so easily: you must change accessors to getCash() and setters to setCash. All this time fixing something not so important that could have been avoided by hiding the implementation details within your class and only giving access to the general interface.
Sure, that's indeed a pretty dumb example, but it happened to me so many times with more complex cases(sometimes the bug is much harder to find) that I've really learned to encapsulate as much as I can. Do your future-self and the viewers of your code a favor and hide private members, you never know when your "implementation details" will change.
When you are on a project where 2 or more people are working on the same project, but you work lets, say, 2 people work on Mondays, 2 on Tuesdays, 2 on Wednesdays, etc. The next people that will continue the project won't have to go bother the other coders just to explain what/when/why it has been that way. If you know TORTOISE you will see it's very helpful.

Inheritance vs specific types in Financial Modelling for cashflows

I have to program some financial applications where I have to represent a schedule of flows. The flows can be of 3 types:
fee flow (just a lump payment at some date)
floating rate flow (the flow is dependant of an interest rate to be determined at a later date)
fixed rate flow (the flow is dependant of an interest rate determined when the deal is done)
I need to keep the whole information and I need to represent a schedule of these flows.
Originally I wanted to use inheritance and create three classes FeeFlow, FloatingFlow, FixedFlow all inheriting from ICashFlow and implement some method GetFlowType() returning an enum then I could dynamic_cast the object to the correct type.
That would allow me to have only one vector<IFlow> to represent my schedule.
What do you think of this design, should I rather use three vectors vector<FeeFlow>, vector<FloatingFlow> and vector<FixedFlow> to avoid the dynamic casts ?
Why do you actually need the dynamic casts? Make your flow subclasses implement the same interface polymorphically, then there is no need to cast anything.
If they need very different inputs, you could try passing the different inputs as constructor parameters, thus clearing up the common interface. However, if you really can't define a common interface for them, maybe they are better implemented as independent classes.
If all the operations you need to do with the different types of the flow differ only by the underlying data, i would suggest extending the ICashFlow with such operations - then no dynamic casting is needed. If however this is not possible, then both options are ok i think. I personally would choose the one with the three vectors, if there is no other hidden need for one vector of base classes.
I think the strategy pattern would suit you best.
You implement a CashFlow class that contains a CashFlowStrategy property which does the processing.
I do not fully understand the requirements and the differences between the flows but something like this might work (meta-c++, not valid code):
class CashFlowStrategy {
public:
virtual void ProcessFlow(Account from, Account to);
}
class FixedRateCashFlowStrategy : public CashFlowStrategy {
public:
void ProcessFlow(Account from, Account to) { ... }
}
class CashFlow {
private:
CashFlowStrategy strategy;
public:
CashFlow(CashFlowStrategy &strategy) { this->strategy = strategy; }
void Process() { this->strategy->ProcessFlow(this->from, this->to); }
}
You only need the std::vector<CashFlow>, the decision of how to do the processing is hidden in the strategy so you shouldn't have to care about it.
It sounds like you have various schedules and various types of deposits, which collectively make up a financial flow. The solution sounds as if a strategy pattern may work for both schedule and deposit behavior. Although, if you have room, it might be worth considering a functional approach. A lambda expression would give you the same logic with a tenth of the code ...

OOP: self-drawing shapes and barking dogs

Most of the books on object-oriented programming I've read used either a Shape class with a Shape.draw() member function or a Dog class with a Dog.talk() member function, or something similar, to demonstrate the concept of polymorphism. Now, this has been a source of confusion for me, which has nothing to do with polymorphism.
class Dog : public Animal
{
public:
...
virtual void talk() { cout << "bark! bark!" << endl; }
...
};
While this might work as a simple example, I just can't imagine a good way to make this work in a more complicated application, where Dog.talk() might need to access sound subroutines of another class, e.g. to play bark.mp3 instead of using cout for output. Let's say I have:
class Audio
{
public:
...
void playMP3(const string& filename)
...
};
What would be a good way to access Audio.playMP3() from within Dog.talk() at design time? Make Audio.playMP3() static? Pass around function pointers? Have Dog.talk() return the filename it wants to play and let another part of the program deal with it?
One way might be to have the Dog constructor take a reference to an instance of an Audio class, because dogs (usually) make noise:
class Dog: public Animal {
public:
Dog(Audio &a): audio(a) {}
virtual void talk() { audio.playMP3("bark.mp3"); }
private:
Audio &audio;
};
You might use it like this:
Audio audioDriver;
Dog fido(audioDriver);
fido.talk();
My solution would be for the Dog class to be passed an audio device in the bark function.
The dog should not store a pointer to the audio device all the time, that's not one of its responsibilities. If you go that route, you end up with the constructor taking two dozen objects, essentially pointing to all the rest of the application (it needs a pointer to the renderer too, so it can be drawn. It needs a pointer to the ground, and to the input manager telling it where to go, and........... Madness lies that way.
None of that belongs in the dog. If it needs to communicate with another object, pass that object to the specific method that needs it.
The dog's responsibility is to bark. A bark makes a sound. So the bark method needs a way to generate a sound: It must be passed a reference to an audio object. The dog as a whole shouldn't care or know about that.
class Dog: public Animal {
public:
virtual void talk(Audio& a);
};
By the same logic, shapes should not draw themselves. The renderer draws objects, that's what it's for. The rectangle object's responsibility is just to be rectangular. Part of this responsibility is to be able to pass the necessary drawing data to the renderer when it wishes to draw the rectangle, but drawing itself is not part of it.
This is a really interesting question as it touches on elements of design and abstraction. For example, how do you put a Dog object together so that you retain control over how it is created? What sort of Audio object should it support and should it 'bark' in MP3 or WAV etc?
It's worth reading through a bit about Inversion of Control and Dependency Injection as a lot of the issues you're thinking about have been thought through quite a bit. There are quite a few implications such as flexibility, maintainability, testing etc.
The callback interface has been suggested in a few of the other answers, but it has drawbacks:
Many (potentially significantly) different classes relying on the same interface. These classes different needs may corrupt the clarity of the interface, what started out as PlaySound( sound_name ) becomes PlaySound( string sound_name, bool reverb, float max_level, vector direction, bool looping, ... ) with a bunch of other methods (StopSound, RestartSound, etc etc)
Changes to the audio interface will rebuild everything that knows about the audio interface (I find this does matter with C++)
The provided interface only works for the audio system (well, it should only be for the audio system). What about the video system, and the networking system?
One alternative that has also been mentioned is to make the audio system calls static (or the audio system interface a singleton). This will keep dog construction simple (creating a dog no longer requires knowledge of the audio system), but doesn't address any of the issues above.
My prefered solution is delegates. The dog defines its generic output interface (IE Bark( t_barkData const& data); Growl( t_growlData const& data ) ) and other classes subscribe to this interface. Delegate systems can become quite complex, but when properly implemented they are no more difficult to debug than a callback interface, reduce recompile times, and improve readability.
An important note is that the dog's output interface does not need to be a separate class that the dog is provided with at construction. Instead pointers to the dogs member functions can be cached and executed when the dog decides it wants to bark (or the shape decides to draw).
A great generic implementation is QT's signals and slots, but implementing something so powerful yourself will prove difficult. If you would like a simple example of something like this in c++ I would consider posting one but if you're not interested I'm not going to take the time out of my Saturday :)
Some drawbacks to delegates (off the top of my head):
1. Call overhead, for things that happen thousands of time a second (IE "draw" operations in a rendering engine) this has to be taken into account. Most implementations are slower than virtual functions. This overhead is utterly insignificant for operations which do not happen extremely frequently.
2. Code generation, mostly the fault of C++'s limited pointer-to-member-function support. Templates are practically a requirement to implement an easy to read portable delegate system.
Mainly depends on what your application is. Passing function pointers to the animals is not a good idea unless you want dogs and cats to use different audio drivers.
The approach with the static playMP3 method is fine. Using a global reference for your audio system is perfectly fine.
A basic answer is that an Animal gets initialized with either an Audio object or a more complex object that contains multiple Audio's. An Animal's talk function then calls a method on this Audio object to produce the talk noise for the animal.
The Dog object initializes the Animal with a particular instance of an Audio object characteristic of Dogs, or (in more complex cases) takes parameters that allow it to build the Audio object to pass to Animal.