How this program implements the concept of abstraction? [duplicate] - c++

This question already has answers here:
What is abstraction? [closed]
(4 answers)
Closed 10 years ago.
Today,i was searching about abstraction and i got this example....how this program implements the concept of abstraction and please also elaborate what is abstraction in c++
#include <iostream>
using namespace std;
class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}

It should be called data abstraction, which is the key source of OOP(not limited to C++).
Quoted from wikipedia:
Data abstraction enforces a clear separation between the abstract
properties of a data type and the concrete details of its
implementation.
In your example, Adder is a data abstraction of an adder, which has two interfaces: addNum and getTotal. This abstraction hides(or encapsulates) the private data(total in this case), only expose its kernel behavior: adding a number and returning the current sum.

You are accessing the public methods for doing your tasks without knowing how the private members are affected. this is nothing but abstraction .
You are moving your hand without knowing how your mind instruct it to move.
Data Abstraction : Hiding unnecessary details . in your case you hide how the total is calculated. you just call the function and your task is done.
Data Encapsulation: Binding data with object. In your case you binded the total with object a. so it's not accessible without a permission.

Think of the constructor and function prototypes only:
class Adder {
Adder(int i);
void AddNum(int num);
int getTotal();
};
The implementation is hidden, abstracted away, and only the prototypes remain.

Related

How to access a private variable which is within a function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include <iostream>
using namespace std;
class Test{
public:
int kk(int b){
return a=b+5;
}
private:
int a;
/*void priv()
{
int a; // How to access a , if this part was not commented
}*/
};
int main()
{
Test kris;
cout<< kris.kk(5)<<endl;
return 0;
}
I was trying to understand the concept of private and public members and the methods to access the private members when they are defined in a class. I wanted to rephrase the question to how to access a variable, which is local to a private function via an object of class "Test" (as defined in the code).
I found the answer to it and experimented it with my own code and i was able to execute the code. Below is the code
#include <iostream>
using namespace std;
class Test{
public:
int xyz_1(){
return xyz_2() ;
}
private:
int xyz_2(){
int a=5;
return a;
}
};
int main()
{
Test kris;
cout<< kris.xyz_1()<<endl<<"Sorry for the confusion"<<endl;
return 0;
}
How to access a private variable which is within a function
You're trying to access a local variable of priv() in the function kk() which is impossible unless the visibility of the variable a is either public or outside the function (in case with classes) under private: (which will make it accessible to all member functions). In a rough way, you're trying to do something:
void fun1() {
int a;
}
void fun2() {
std::cout << a;
}
Which is not possible.
You might need to think more about your design and what you achieve.
Do you want to have a private member in the class to access the function? Then declare your variable "a" as a private member in your class, and use this.a inside your function. If you want a child class to be also able to access your private member, make the variable protected instead of private.
If you want to restrict any other function in your class from accessing that member, then I would be curious about what your intention is. If you try to hide the implementation you might want to look into the Pimpl technique. However, it also has a very specific use case (besides that you can use it to hide the implementation from developers, too).
https://en.cppreference.com/w/cpp/language/pimpl[pimpl programming technique]1
If you add more information about your problem and intention I'm sure people can give you better directions.

Change base class from derived class permanently?

So, my problem is that i want to modify my parent class Board from a derived class in such a way that it applies to all other objects of the derived class. Ex. If I input a 3 on getTest() in players[1] players[2] will be able to print that same value. Is this posible?
class Board {
public:
int test;
virtual void getTest() = 0;
};
class Player : public Board{
public:
int playerNum;
Player(int _playerNum){
playerNum = _playerNum;
}
void printTest(){
cout << "The value of test is: " << Board::test;
}
void getTest(){
cin >> Board::test;
}
};
int main(){
Player players[] = {1,2};
players[1].getTest();
players[0].printTest();
return 0;
}
It is indeed possible to share state between all instances that derive from Board.
As mentioned in the comments, if Board::test were given the static storage-class duration, this would be a variable shared across all instances of Player and any other classes that derive from Board now and forever. Technically, the variable is actually a member of the type rather than instances of the type. This will work, however in terms of design, it has some strange implications.
Namely, Player::getTest() is a non-static member-function, which sets static state that will be shared across all derived classes of Board. This can work as a quick and dirty change to code, but can lead to maintenance burdens and cognitive overhead. For example, if you have code in different subsystems like a Player and Widget that both implement Board, you get into a case where:
// subsystem A:
player.getState();
// subsystem B:
widget.printTest(); // not obvious that this comes from the player in "subsystem A"
The bigger the code gets, the harder it is to understand.
Additionally, static variables have issues working across translation units that can lead to initialization-order problems -- and it's often a mess that's not worth fighting with.
Depending on what it is you actually intend to share, often times it can be better for design to explicitly state as such using an object that explicitly indicates its shared ownership -- such as a std::shared_ptr.
This won't be implicitly passed to everything as you originally requested -- but that's actually a good thing since you can explicitly state what data you want shared and where. This also lets you decide if ever there's a case where you don't want everything shared between them, you can design it as such.
A simple example with your current code would instead be done like:
class Board {
public:
virtual void getTest() = 0;
};
class Player : public Board{
public:
int playerNum;
std::shared_ptr<int> test;
Player(int _playerNum, std::shared_ptr<int> _test){
playerNum = _playerNum;
test = _test;
}
void printTest(){
cout << "The value of test is: " << *test;
}
void getTest(){
cin >> *test;
}
};
int main(){
std::shared_ptr<int> test = std::make_shared<int>(0);
// explicitly share 'test' between the two players
Player players[] = {Player{1,test}, Player{2,test}};
players[1].getTest();
players[0].printTest();
return 0;
}
This would produce the same results as you originally requested, but it explicitly shared test rather than implicitly doing this behind static variables.
Explicitly stating the shared state here also allows you to produce more Player objects later that might share a different set of test state than the first created ones (depending on what this state is, this can be quite useful).
Overall, it's often better in terms of design for readability and overall cognitive overhead to be explicit about the data you want shared.

Cast relatives classes to each other which has common parent class

I have classes DBGameAction and ServerGameAction which has common parent class GameAction. Classes DBGameAction and ServerGameAction it's a API for safety working with entity GameAction from different part of program.
My question is: is it normal at first create DBGameAction entity and then cast it to the ServerGameAction entity? Or maybe it's a wrong program design?
My program:
#include <vector>
#include <string>
#include <iostream>
class GameAction
{
protected:
/* Need use mutex or something else for having safety access to this entity */
unsigned int cost;
unsigned int id;
std::vector<std::string> players;
GameAction(){}
public:
unsigned int getCost() const
{
return cost;
}
};
class DBGameAction : public GameAction
{
public:
void setCost(unsigned int c)
{
cost = c;
}
void setId(unsigned int i)
{
id = i;
}
};
class ServerGameAction : public GameAction
{
ServerGameAction(){}
public:
void addPlayer(std::string p)
{
players.push_back(p);
}
std::string getLastPlayer() const
{
return players.back();
}
};
int main(int argc, char *argv[])
{
DBGameAction *dbga = 0;
ServerGameAction *sga = 0;
try {
dbga = new DBGameAction;
}
catch(...) /* Something happens wrong! */
{
return -1;
}
sga = reinterpret_cast<ServerGameAction*>(dbga);
sga->addPlayer("Max");
dbga->setCost(100);
std::cout << dbga->getCost() << std::endl;
std::cout << sga->getLastPlayer() << std::endl;
delete dbga;
sga = dbga = 0;
return 0;
}
It is wrong program design.
Is there a reason why you are not creating GameAction variables which you then downcast to DBGameAction and ServerGameAction?
I haven't used reinterpret_cast in many occasions but I am sure it shouldn't be used this way. You should try to find a better design for the interface of your classes. Someone who uses your classes, doesn't have a way to know that he needs to do this sort of castings to add a player.
You have to ask yourself, if adding a player is an operation that only makes sense for ServerGameActions or for DBGameActions too. If it makes sense to add players to DBGameActions, then AddPlayer should be in the interface of DBGameAction too. Then you will not need these casts. Taking it one step further, if it is an operation that makes sense for every possible GameAction you may ever have, you can put it in the interface of the base class.
I have used a similar pattern effectively in the past, but it is a little different than most interface class setups. Instead of having a consistent interface that can trigger appropriate class-specific methods for accomplishing similar tasks on different data types, this provides two completely different sets of functionality which each have their own interface, yet work on the same data layout.
The only reason I would pull out this design is for situations where the base class is data-only and shared between multiple libraries or executables. Then each lib or exe defines a child class which houses all the functionality that it's allowed to use on the base data. This way you can, for example, build your server executable with all kinds of nice extra functions for manipulating game data that the client isn't allowed to use, and the server-side functionality doesn't get built into the client executable. It's much easier for a game modder to trigger existing, dormant functionality than to write and inject their own.
The main part of your question about casting directly between the child classes is making us worry, though. If you find yourself wanting to do that, stop and rethink. You could theoretically get away with the cast as long as your classes stay non-virtual and the derived classes never add data members (the derived classes can't have any data for what you're trying to do anyway, due to object slicing), but it would be potentially dangerous and, most likely, less readable code. As #dspfnder was talking about, you would want to work with base classes for passing data around and down-cast on-demand to access functionality.
With all that said, there are many ways to isolate, restrict, or cull functionality. It may be worth reworking your design with functionality living in friend classes instead of child classes; that would require much less or no casting.

Flexible design despite strongly dependent classes

I'm working on a code which needs to be extremely flexible in nature, i.e. especially very easy to extend later also by other people. But I'm facing a problem now about which I do not even know in principal how to properly deal with:
I'm having a rather complex Algorithm, which at some point is supposed to converge. But due to its complexity there are several different criteria to check for convergence, and depending on the circumstances (or input) I would want to have different convergence criteria activated. Also it should easily be possible to create new convergence criteria without having to touch the algorithm itself. So ideally I would like to have an abstract ConvergenceChecker class from which I can inherit and let the algorithm have a vector of those, e.g. like this:
//Algorithm.h (with include guards of course)
class Algorithm {
//...
vector<ConvergenceChecker*> _convChecker;
}
//Algorithm.cpp
void runAlgorithm() {
bool converged=false;
while(true){
//Algorithm performs a cycle
for (unsigned i=0; i<_convChecker.size(); i++) {
// Check for convergence with each criterion
converged=_convChecker[i]->isConverged();
// If this criterion is not satisfied, forget about the following ones
if (!converged) { break; }
}
// If all are converged, break out of the while loop
if (converged) { break; }
}
}
The problem with this is that each ConvergenceChecker needs to know something about the currently running Algorithm, but each one might need to know totally different things from the algorithm. Say the Algorithm changes _foo _bar and _fooBar during each cycle, but one possible ConvergenceChecker only needs to know _foo, another one _foo and _bar, and it might be that some day a ConvergenceChecker needing _fooBar will be implemented. Here are some ways I already tried to solve this:
Give the function isConverged() a large argument list (containing _foo, _bar, and _fooBar). Disadvantages: Most of the variables used as arguments will not be used in most cases, and if the Algorithm would be extended by another variable (or a similar algorithm inherits from it and adds some variables) quite some code would have to be modified. -> possible, but ugly
Give the function isConverged() the Algorithm itself (or a pointer to it) as an argument. Problem: Circular dependency.
Declare isConverged() as a friend function. Problem (among others): Cannot be defined as a member function of different ConvergenceCheckers.
Use an array of function pointers. Does not solve the problem at all, and also: where to define them?
(Just came up with this while writing this question) Use a different class which holds the data, say AlgorithmData having Algorithm as a friend class, then provide the AlgorithmData as a function argument. So, like 2. but maybe getting around circular dependency problems. (Did not test this yet.)
I'd be happy to hear your solutions about this (and problems you see with 5.).
Further notes:
Question title: I'm aware that 'strongly dependent classes' already says that most probably one is doing something very wrong with designing the code, still I guess a lot of people might end up with having that problem and would like to hear possibilities to avoid it, so I'd rather keep that ugly expression.
Too easy?: Actually the problem I presented here was not complete. There will be a lot of different Algorithms in the code inheriting from each other, and the ConvergenceCheckers should of course ideally work in appropriate cases without any further modification even if new Algorithms come up. Feel free to comment on this as well.
Question style: I hope the question is neither too abstract nor too special, and I hope it did not get too long and is understandable. So please also don't hesitate to comment on the way I ask this question so that I can improve on that.
Actually, your solution 5 sounds good.
When in danger of introducing circular dependencies, the best remedy usually is to extract the part that both need, and moving it to a separate entity; exactly as extracting the data used by the algorithm into a separate class/struct would do in your case!
Another solution would be passing your checker an object that provides the current algorithm state in response to parameter names expressed as string names. This makes it possible to separately compile your conversion strategies, because the interface of this "callback" interface stays the same even if you add more parameters to your algorithm:
struct AbstractAlgorithmState {
virtual double getDoubleByName(const string& name) = 0;
virtual int getIntByName(const string& name) = 0;
};
struct ConvergenceChecker {
virtual bool converged(const AbstractAlgorithmState& state) = 0;
};
That is all the implementers of the convergence checker need to see: they implement the checker, and get the state.
You can now build a class that is tightly coupled with your algorithm implementation to implement AbstractAlgorithmState and get the parameter based on its name. This tightly coupled class is private to your implementation, though: the callers see only its interface, which never changes:
class PrivateAlgorithmState : public AbstractAlgorithmState {
private:
const Algorithm &algorithm;
public:
PrivateAlgorithmState(const Algorithm &alg) : algorithm(alg) {}
...
// Implement getters here
}
void runAlgorithm() {
PrivateAlgorithmState state(*this);
...
converged=_convChecker[i]->converged(state);
}
Using a separate data/state structure seems easy enough - just pass it to the checker as a const reference for read-only access.
class Algorithm {
public:
struct State {
double foo_;
double bar_;
double foobar_;
};
struct ConvergenceChecker {
virtual ~ConvergenceChecker();
virtual bool isConverged(State const &) = 0;
}
void addChecker(std::unique_ptr<ConvergenceChecker>);
private:
std::vector<std::unique_ptr<ConvergenceChecker>> checkers_;
State state_;
bool isConverged() {
const State& csr = state_;
return std::all_of(checkers_.begin(),
checkers_.end(),
[csr](std::unique_ptr<ConvergenceChecker> &cc) {
return cc->isConverged(csr);
});
}
};
Maybe the decorator pattern can help in simplifying an (unknown) set of convergence checks. This way you can keep the algorithm itself agnostic to what convergence checks may occur and you don't require a container for all the checks.
You would get something along these lines:
class ConvergenceCheck {
private:
ConvergenceCheck *check;
protected:
ConvergenceCheck(ConvergenceCheck *check):check(check){}
public:
bool converged() const{
if(check && check->converged()) return true;
return thisCheck();
}
virtual bool thisCheck() const=0;
virtual ~ConvergenceCheck(){ delete check; }
};
struct Check1 : ConvergenceCheck {
public:
Check1(ConvergenceCheck* check):ConvergenceCheck(check) {}
bool thisCheck() const{ /* whatever logic you like */ }
};
You can then make arbitrary complex combinations of convergence checks while only keeping one ConvergenceCheck* member in Algorithm. For example, if you want to check two criteria (implemented in Check1 and Check2):
ConvergenceCheck *complex=new Check2(new Check1(nullptr));
The code is not complete, but you get the idea. Additionally, if you are a performance fanatic and are afraid of the virtual function call (thisCheck), you can apply the curiously returning template pattern to eliminate that.
Here is a complete example of decorators to check constraints on an int, to give an idea of how it works:
#include <iostream>
class Check {
private:
Check *check_;
protected:
Check(Check *check):check_(check){}
public:
bool check(int test) const{
if(check_ && !check_->check(test)) return false;
return thisCheck(test);
}
virtual bool thisCheck(int test) const=0;
virtual ~Check(){ delete check_; }
};
class LessThan5 : public Check {
public:
LessThan5():Check(NULL){};
LessThan5(Check* check):Check(check) {};
bool thisCheck(int test) const{ return test < 5; }
};
class MoreThan3 : public Check{
public:
MoreThan3():Check(NULL){}
MoreThan3(Check* check):Check(check) {}
bool thisCheck(int test) const{ return test > 3; }
};
int main(){
Check *morethan3 = new MoreThan3();
Check *lessthan5 = new LessThan5();
Check *both = new LessThan5(new MoreThan3());
std::cout << morethan3->check(3) << " " << morethan3->check(4) << " " << morethan3->check(5) << std::endl;
std::cout << lessthan5->check(3) << " " << lessthan5->check(4) << " " << lessthan5->check(5) << std::endl;
std::cout << both->check(3) << " " << both->check(4) << " " << both->check(5);
}
Output:
0 1 1
1 1 0
0 1 0

Class and Member Function (beginner)

I'm currently reading a c++ book, and I have a few questions.
1) Is void only used to declare a return type in this example?
2) If void causes it NOT to return data to the calling function, why is it still displaying the message "Welcome to the Grade Book!"?
3) Isn't it easier to create a simple function instead of making an object?
#include <iostream>
using namespace std;
class GradeBook
{
public:
void displayMessage()
{
cout << "Welcome to the Grade Book!" << endl;
}
};
int main()
{
GradeBook myGradeBook;
myGradeBook.displayMessage();
}
That's the only use in this example. You can also have pointers to void (void *).
You're not returning that message. You're printing it. In C++, methods and functions can have side effects. One possible side effect is output.
Yes, in this case. However, this is not a realistic example of the benefits of objects. For that, see How do I describe Object-Oriented Programing to a beginner? Is there a good real-world analogy? among many places.
Is void only used to declare a return type in this example?
Yes, it indicates that displayMessage() will not return back anything to it's caller.
It can also be used as a void *, i.e: A generic pointer which can point to anything, but it is not being used in that way in your example.
If void causes it NOT to return data to the calling function, why is it still displaying the message "Welcome to the Grade Book!"?
The message is not returned to the caller of the function, the message is directed to the standard output when the control was in the function and executing that particular statement.
Isn't it easier to create a simple function instead of making an object?
It's not a matter of ease. It is more of an matter of Object Oriented design principles.
The purpose of having classes and member functions is to bind together the data and the methods that operate on that data in a single unit. You might want to pick up a good book and read up Encapsulation & Abstraction.
The Definitive C++ Book Guide and List
In your case the function "displayMeassage" is not returning the string, it is just printing your message.
Returning means, suppose an example:
class A
{
int num=0;
int getNum()
{
return num;
}
};
void main()
{
A a;
int no=a.getNum();
cout<<"no : "<<no;
}
In above example, then way getNum is returning the number that is what returning is
called.
Whatever you are taking the example is not good to understand the return concept.
Thanks