Is this bad practice or normal? [closed] - c++

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 9 years ago.
Improve this question
Say for example I have two classes.
I know that one way is to pass a pointer to the Foo object in the constructor and then use that inside Object, but is this a good way to approach things?
Is there something else more appropriate?
Thanks.
class Object
{
private: //etc
public:
void doStuff()
{
//access the foo object (x) created in main.
}
};
class Foo
{
private: //etc
public:
void function()
{
Object * obj = new Object();
obj->doStuff();
}
};
int main(int args, char**argv)
{
Foo * x = new Foo();
x->function();
return 0;
}

It depends on what you have to do.
If your doStuff() method must know the content of the given object you can't use this way. Otherwise, if you, like in the example you post, your doStuff method has just to create an object for performing an internal operation you may use this approach.
Generally, there is not a better or a worse way of operating. It always depends.
An example.
Your doStuff method needs something from the external in order to do something:
class Foo
{
private: //etc
public:
void function(Object* obj)
{
obj->doStuffWithTheGivenObject();
}
};
}
Your doStuff method needs nothing from external:
class Foo
{
private: //etc
public:
void function()
{
Object* obj = new Object();
obj->doStuffModifyingTheGivenObject();
this->doStuffOnThisFooObjectWithTheJustCreatedObject(obj);
}
};
}
In the second case your Foo object does not need an Object, because it can independetly create an object by itself for using it internally.
In the first case, instead, it is waiting for an Object because it uses that one for doing something.
The difference stays in: "Do I need an object or I can create that internally?"

It might help here to know what "Foo" and "Object" actually are. If "Object" actually is "Fruit" and "Foo" is an "Apple" than inheritance makes sense. Alternatively if "Object" represents some sort of stream and "Foo" represents a class that depends on the stream, then what you are doing makes sense. Its all going to depend on what you are trying to accomplish here.

Related

How to access the new member functions of child class? [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 4 years ago.
Improve this question
I have 2 classes:
#include <iostream>
using namespace std;
class A
{
public:
virtual void print()=0;
};
class B: public A
{
public:
void print()
{
cout<<"B\n";
}
void printNew()
{
cout<<"Print new";
}
};
int main()
{
B b;
A *a=new B;
a->printNew();
delete a;
}
The compiler posts an error. If I want to use printNew through A, how can I do it? I thought it must include this feature because this proves useful in various situations.
Having a subclass instance B in a superclass A pointer is called Polymorphism in OOP.
From this A-type pointer, you would not be able to see the member function which exists only in B-type, clearly.
You could use this object as a B-type object by downcasting it though:
B *B = dynamic_cast<B*>(a);
As a has a dynamic type of B*, the cast is safe so a B pointer is returned.
Polymorphism doesn't work like that.
Although a has a dynamic type B*, its static type is A* and as such the pointer to member operator -> cannot reach the printNew function.
Crudely, you could write
virtual void printNew() { cout << "printNew() not implemented";}
in class A.
From C++20 it might indeed be possible to do as you want using reflection, with albeit different calling syntax.

Private getters and setters [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I am still new to C++ and OOP programming, and I was just wondering about something curious.
I have a class let's name it Foo, with some private members.
My question is: the Foo objects don't "pass data" to other objects during their lifespan. They receive data, do things, and save new data to file. That means, only Foo objects will access Foo private members.
Is it wrong to implement private getters and setters?
Or should I use direct access?
Pseudo code below:
Is this okay?
class foo
{
private:
string a;
string b;
string c;
void setA(string A){this->a=A;}
string getA()const{return this->a;
void setB(string B){this->b=B;}
string getB()const{return this->b;
void setC(string C){this->c=C;}
string getC()const{return this->b;
public:
//many omitted methods//
void Method(); //<-- this method does things and calls private getters and setters to modify private members
}
In main:
{
Foo obj=....;
obj.Method();
}
Or should I:
class foo
{
private:
string a;
string b;
string c;
public:
//many omitted methods//
void Method();
}
void foo::method()
{
string s1;
//initialize s1;
this->a=s1; //operation example
std::cout<<"A equals: "<< this->a;
}
Not sure if I explained my concerns in simple way.
Thank you in advance for your replies and help.
Writing private "getters" and "setters" is pointless, unless you are exploiting polymorphism in some funny way.
Setting up your member variables via a constructor is the best thing to do, and making the members const prevents their unintentional modification.
Avoid "setters" whenever possible regardless of their accessibility as they do little more than circumvent encapsulation.
I'm not the most experienced C++ developer, but from my point of view, using direct access is not a bad practice and it will require less time to write.
On the other hand, having such members in your interface makes it clear that only the Foo objects could read Foo's private members, so both ways are acceptable.
The main point of having getters and setters is controlling access to the class members in a flexible and extensible way. You don't get anything from creating getters and setters if you know they will never be used by external clients of the class, so I would advice to not write them at all.
They will only clutter your source files and make your code harder to read.
By they way, you don't need to use this everytime you want to access a member:
class foo {
private:
string a;
string b;
string c;
public:
//many omitted methods//
void Method();
}
void foo::method() {
string s1;
a=s1;
std::cout<<"A equals: "<< a;
}

Define enum in class or in File? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Say that in file foo.h I have:
enum bar {
ONE = 1,
TWO
};
class foo {
bar m_bar;
public:
void setBar(bar arg){ m_bar = arg; }
bar getBar() const { return m_bar; }
};
In my current design, the only persistent bar variable will be m_bar. But I will have other functions, outside of foo that contain a bar, for example a GUI class that creates a local bar and passes it to setBar.
So here's my question, is there any rationale to defining bar publicly inside foo versus just inside the class where it is?
So here's my question, is there any rationale to defining bar inside foo versus just inside the class where it is?
If all the functions that create/work with bar are related to foo functionality, then it is perfectly acceptable to write it like this:
class foo
{
enum bar {
ONE = 1,
TWO
};
};
void process_bar_of_foo(foo::bar bar_value); // process the bar of a foo
If on the other hand you can write code that has (conceptually) nothing to do with a foo instance but deals with bar values, you should probably write it separately.
Well, as it stands, you can create bar objects with objects and functions outside of the foo class like you mentioned and then pass it to whatever foo object you make.
If you were to, however, define it in the class, then you wouldn't really be able to make bar objects unless you create a foo class first which can lead to unnecessary overhead if you just want to enum object.
And so it really depends on what you're going to do. If you only plan on using bar with the foo class, then it would be perfectly acceptable to define it there. Otherwise if it's going to be accessed elsewhere, leave it as is.

Crashing on calling virtual methods [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I read about it in other questions but none of them was similar, some was about to call a virtual method in the constructor, others about pure virtuals, but the question here is about vituais methods that are not pure, but about virtual methods that doesn't need be implemented in all derivatives classes. If the class instantiated doesn't implements the method, if we call, it logically calls the method from the base and it crashes sometimes.
I was wondering, why? What is VTABLE (where it enters)? And what is the best way to solve it.
This is a simple example, (avoid answer like pure virtual).
#include <iostream>
class Foo
{
public:
virtual std::string myString() {}
};
class Bar : public Foo
{
public:
};
int main(int argc, char ** argv)
{
Foo * bar = new Foo;
bar->myString();
return 0;
}
What would be the best solution?
Throw an exception
Using assert(false)
Returning a default value
Avoid implementing a body and it will result in an error in
compilation time
None of the alternatives
The best answer will be the one that explains why this happen based on VTABLE and of course, that choose one solution and explain why. The idea is not to base it on opinions.
The base class does implement the function, it just implements it wrong. It is not related to vtables or anything sophisticated. Solution 4 preferred (since it prevents building wrong programs), if not possible/desired 1 or 2 in that order.
Note that the error is not at all related to virtual functions, or inheritance in general (you do not use Bar, did you notice?). It is not even related to classes at all but would happen with any freestanding function as well. Consider:
#include <iostream>
#include <string>
// Note: UB -- nothing returned
int getInt() {}
std::string getStr() {}
int main(int argc, char ** argv)
{
// This probably works (read access from an arbitrary
// location on the stack which is in the prog's address space)
std::cout << getInt() << std::endl;
// This will crash. operator<< will try to access memory through
// a pointer value which is some arbitrary byte pattern on the stack.
// Probably not in the prog's address space.
// Then the destructor for the temporary string will
// try to delete the same
// memory which will crash in any case, even if it happens to
// point to valid memory (which, alas, was never allocated).
std::cout << getStr();
std::cout << "Still alive?\n"; // never printed
std::cout.flush();
return 0;
}
In order to prevent the error from happening with your original code, just return a value. If you implement the function and don't throw or abort (which are the three alternatives), i.e. if you return, you must return a value:
#include <iostream>
class Foo
{
public:
virtual std::string myString() { return "test\n";}
};
class Bar : public Foo
{
public:
};
int main(int argc, char ** argv)
{
Foo * bar = new Foo();
std::cout << bar->myString();
return 0;
}
The VTABLE is a table of pointers to virtual methods. In general, the pointer to the VTABLE is hidden from view, but it is often implemented as the first element in an instance of a class.
When a derived class does not have a member function that its parent class does implement as virtual, the parent's method will be called.
Your mystring function should return a string.

questiong regarding memory optimzation C++ [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 9 years ago.
Improve this question
I have header file as something like following.
class A;
class B;
class C;
Class a {
A *a;
B *b;
C *c;
};
Now, Class a does not using all A, B, C and around 40 others. I have around 40 forward declarations... Is possible to optimize it someone.. So, I can declared pointer to class on need bases instead of wasting memory for all pointer to all 40 odd class?
You can use union with type code or boost::variant
I would recommend for now that you should make a parent class and put as children all of the A,B,C,etc... Then in class use a list of the parent class, and put whatever subclass you need on it. But having this problem is actually due to wrong object oriented design. Learn the principles of OO design of a system in Java for example and then put them in use in C++.
Admitting you cannot rework your classes, and admitting you are using only one at time, you can use a union plus an ID or a "dynamically typed void*":
unsigned gen_id()
{ static unsigned id=0; ++id; return id; }
template<class T>
unsigned id_of()
{ static id = gen_id(); return id; }
class a
{
void* m;
unsigned type;
public:
template<class T>
a(T* p) :m(p), type(id_of<T>())
{}
template<class T>
T* get() const
{ return (id_of<T>()==type)? static_cast<T*>(m): nullptr; }
};
You can access a data as
A* pa = my_a.get();
if(pa) { /* what has to be done with A */ }
If you need more than one, consider a class b holding a vector of a.
For a more "standardized" implementation you can look at boost::any