How to work around a getter that also sets a member? - c++

I'm dealing with something that goes along these lines:
I have a class that is quite complex and a member that depends on some stuff that isn't set when the class is initialized, or is set on the go. Objects of that class make sense even when that member isn't set. It can also be reset depending on other changes that are made to other members.
Now, assume this "special" member is computationally-expensive to set, and so I'm delaying computing it on request.
So:
class Class
{
X x;
Y y;
SpecialClass specialObject;
public:
void setX(const X& newX);
void setY(const Y& newY);
//----
SpecialClass getSpecialObject() /*const*/
{
computeSpecialObject();
return specialObject();
}
private:
void computeSpecialObject()
{
//specialObject depends on x and y
//and is expensive to compute
//this method is a bottleneck
}
};
I don't want to call the compute method every time I change x or y because it's expensive, so I'm left with the dilemma:
remove the const? Logically, the getter should be const, but it can't. There's also the downside that it can't be called on const objects.
I can make specialObject mutable, but it doesn't seem like the right thing to do.
cast away constness? Again, looks fishy.
call computeSpecialObject before the get? - what if someone forgets? They'll get an out-dated result.
Is there a design pattern that deals with this? A good approach? Or is the class design just wrong? (I'd lean towards this last one, but changing the class isn't really an option)
Note: I've made the member mutable, want to know if there's a better solution.

I can make specialObject mutable, but it doesn't seem like the right thing to do.
Why so? That's exactly why mutable exists: to allow a const function to be logically const without the need to physically leave the object unchanged (and if you make the object mutable, remember about ensuring thread-safety - I'm sure you know what I mean).
This is true as long as the initialization of the SpecialClass object is not something that alters the logical state of the object, of course, because that's what const promises not to do.
In that case, the function itself is simply not const in nature, and it should likely be named something different than just getSpecialObject(): computeAndReturnSpecialObject() could be a candidate.

I'd leave the const and either make specialObject mutable or keep a pointer to the specialObject instead of just 'embedding' it into the class.
I would also add a bool dirty flag that is mutable and set it whenever a change is made that invalidates the computation. I would then check the flag inside computeSpecialObject and do the work only if it's set. Using a pointer, you could even delete the old computation object whenever a change invalidates an existing computation, but that opens a whole 'nother can of worms.
Or am I missing something?

It's always a fine line this one, not calling it when you don't need to, versus introduces holes in caller, that mean it might not have been and returning incorrect results.
Me I'd move compute to be method of special object and the treat this class as a wrapper for the arguments for the compute method that class. A bonus ball is you can unit test the computation.
Then it's just a question of deciding when you need to call SpecialObject.Compute(x,y) again or simply return the last result.
Another thing I might look at if I could, would be if X has changed but Y hasn't can I simplify the calculation. i.e. keep some intermediate results.
Not sure how applicable it is for you, but one of the things I regularly end up doing is injecting a something that does the compute, so I tend to fall into this pattern by default.

There are two directions you could go, more OOP or more Functional. One involves caring less about state manipulation, but rather behaviour, the other completely forgets about behaviour, and cares about returned state.
OOP
For me a key OOP principle is Tell, Don't Ask, or write no getters or setters.
Design your objects to be told what to do, to be autonomous. Don't ask it to return some object which you can then use to do something. Just tell it to do the thing you want in the first place. If you're telling an object to do something then you likely expect it to change state, and it's not right for it to be const.
Your SpecialClass may provide some service doService(). You can instead tell Class to doSpecialService(), which is rightly mutable.
An alternative is for the creation of this object to use some other object to do the creation. So a function can be const but take a non const parameter:
class Class {
public:
void doService(ServiceProvider& serviceProvider) const {
serviceProvider.doService(x, y);
}
};
With this you would pass in a SpecialServiceProvider& which would create the correct SpecialClass for the given X and Y. It would be mutable. It would seem correct to modify state in the provision of the service. Maybe you could have a map caching SpecialClass objects for (X, Y) pairs.
Functional
The other direction is to make your objects immutable. Whenever you want some new state create it using the old state as a basis. This could have a knock on effect until you have turtles (almost) all the way down:
class SpecialBuilder {
public:
SpecialBuilder withX(const X& newX) const;
SpecialBuilder withY(const Y& newY) const;
SpecialClass build() const;
};
SpecialBuilder specialBuilder;
SpecialClass special = specialBuilder.withX(x).withY(y).build();
You can share data between each returned SpecialBuilder as it is immutable.

Related

Check current value before assignment in set method

I'll start from a code snipped of an application I found over the internet. It's made in C++ but the topic could be addressed to any programming language:
class AppSettings
{
public:
AppSettings() {m_value = 0;}
~AppSettings();
void AppSettings::setValue(uint value)
{
if (m_value != value)
m_value = value;
}
private:
uint m_value;
};
Do you really need to check that the current value differs from the new one before assignment?
Is it just a programming style, efficiency, good manner, or what?
General speaking, in set method of a class, do you need to check that new value differs from current one?
This largely depends on the type of the member being assigned. If it's a primitive type or something equally lightweight, the check is most likely a pessimisation: the assignment is likely to be significantly cheaper than the conditional jump. Remember that basically all modern processors are pipeline-based, and conditional jumps can result in the pipeline needing to be aborted if branch prediction fails. This kills efficiency.
If the type is much more costly to assign, the answer is not so clear-cut. Copying a large buffer of data, for example, is an expensive operation. However, so is comparing it for equality. To make the call on whether to assign blindly or compare first, you need to understand the idiosynracies of the type in question, and evaluate how often same-value assignments are likely to happen, how quick they are to identify, and how costly this identification is compared to copying "blindly." Also bear in mind that if the comparison indicates they the values are different, you will have paid for both: the comparison, and then the copy.
Finally, there are cases when the check is necessary: when the assignment has a side effect. For example, if the type of the member is such that it emits a notification whenever assigned to, you will most likely need the comparison to avoid spurious notifications (assuming you don't want those, of course).
In all, there is no hard-and-fast rule, but I would say that on average, you should only include the comparison if you have good reason for it.
Do you really need to check that the current value differs from the new one before assignment? Is it just a programming style, efficiency, good manner, or what?
It looks like cruft to me.
You usually end up with code like this, when you mix two ideas while writing the code ("We only update state when necessary" vs. "the setter just sets the value"), and the sample code ends up not expressing either idea clearly.
I cannot say though - I would have to read the article you took the code from.
General speaking, in set method of a class, do you need to check that new value differs from current one?
You do, when you either optimize, or when the idea you need to express in code is "perform updates when necessary".
Consider this (artificial and contrieved) code:
/// object in 2D space
class TwoDObject
{
/// shift object position
void shift_position(int x, int y)
{
if(x != x_ || y != y_)
{
x_ = x;
y_ = y;
render_shadows();
}
}
private:
// render the shadows cast by this object (slow implementation)
void render_shadows();
int x_;
int y_;
};
In this case, you have an internal state update, followed by side effects (shadows have changed when you changed position).
Because the method to render the shadows is slow, you only want to call it when necessary.
It really depends on what you are setting, what I mean, It is important to do it if you are setting things that will propagate changes. If the cost of that change is quite big(reorder an entire array, update data in some network place, rewrite a big file) in this cases, and if the program needs real time performance, it is a good practice to check unnecesary changes. If the change has no side-effects is better just change it and avoid extra branching.

Is it better to update the value or change the pointer?

C++
Is it better to update the value of a pointer or to change the pointer to point to something else?
Let's say we have two classes: ball and coordinates.
class ball
{
Coordinates *ballCurrent;
public:
ball(int);
~ball();
void setLoc(Coordinates&); // OR void setLoc(int, int);
};
class Coordinates
{
int x, y;
public:
Coordinates(int, int);
void setCoordinates(int, int);
};
For the setLoc method in the ball class, which parameters should is better? Would it be better to just setLoc by using (*ballCurrent).setCoordinates(int, int) OR by using (ballCurrent).setLoc((new Coordinates(int, int)))? Please go into detail the reason for each case if possible.
Is it better to update the value of a pointer or to change the pointer
to point to something else?
That's not the sort of question that can be answered without some context. It's often useful to know that an object is immutable -- that as long as you have a pointer to that object, the object won't change under your nose. For example, if a function or method takes a pointer to an immutable type as a parameter, you know that you can pass objects to that function without worrying that the function will change the object.
On the other hand, mutable objects also have their place. For one thing, you sometimes want to be able to build an object up in several steps rather than doing it all at once, and you may not want to have to create several intermediate objects along the way just to get to the final object.
So, it depends on context. I see that you've provided a simple example, but I don't think there's necessarily a correct answer even for your example. It depends on what's important to you and how the objects in question will interact with other parts of the system. I'd lean toward mutable objects, I think, because in a game it's likely that several objects will need to know about the ball. If the only way to move the ball is to create a new ball and pass it around to all the other objects that care about it, well, that could easily get to be a huge problem. The coordinates object could easily be immutable, though -- anyone who needs to know the location of the ball should ask the ball for it's location. Once they get it, they'll probably expect the location not to change every few milliseconds. If you don't make the coordinates object immutable, the other way to handle that problem is for the ball to make a copy of its location whenever someone asks, and hand out that copy instead of returning a pointer to its own location object.
I might write this way if I could:
class ball
{
Coordinates coordinate_; // better name than ballCurrent?
public:
explicit ball(int) // add explicit to avoid implicit converting
: coordinate_(0,0) // initialize corrdinate_ properly
{
}
~ball();
void setLoc(const Coordinates& co) // add const
{
coordinate_ = co;
}
void setLoc(int x, int y)
{
coordinate_.setCoordinates(x,y);
}
};
No need to worry about dynamic memory issue, could setLoc in two ways by function overloading. No wild pointer, no worries.
If you use a new object, it will need memory allocated for itself, and it will also need to be initialized (constructor/s run, properties assigned, etc). That is a lot of overhead compared to just change the value of an object you already have (and that you created for that very purpose).
Besides, if you create a new object, you need to free the memory of your previous pointer, which again is overhead... so just change your existing object.
Just change the values of the object that is being pointed to. It doesn't make sense to create a whole new object every time you want to update a value.
One situation where you might have to create a whole new object rather just change the values is if Coordinates had a const x and y value and there was no setCoordinates function. But then that's mostly likely a poor design decision if you are needing to be update the co-ordinates often.
Also rather than this:
(*ballCurrent).setCoordinates(int, int);
you can use this:
ballCurrent->setCoordinate(int, int);
Which does the same thing but is just easier to write and a lot of people will find it more readable.
In the case of SetLoc(int,int), you are creating a dependency between ball and Coordinates on the Coordinates constructor, and more importantly, on what it represents. If the constructor signature changes, you will have to carry these changes over to ball::SetLoc. This argument is valid in the general case, where you really want to avoid passing along a set of parameters to initialize an object component.
In this particular case, Coordinates embodies an position in space, and probably should come with a set of methods to manipulate it, in order to preserve its implementation details from pervading the rest of the programme. If you wish to move to a 3D coordinate system, ideally, all you would have to change are the constructors invocations and the class implementation. So you really want to reduce the necessary changes outside the class to a minimum, which means avoiding the issue explained earlier.
You present two different solutions to set the location of the ball object. In practice would these solutions appear? In a trivial programme, where the ball position hardcoded, that is a possibility, and either solution could work. But in a more sophisticated software, the ball position would probably be initially set by a configuration file, and any subsequent update of the position done after some non trivial computation. In this situation, it much more maintainable to encapsulate all the logic pertaining to coordinates in the class, and avoid the (int, int) parameter passing.
If you are concerned by memory allocation overheads (e.g. temporaries generated by function returned results), there are ways to alleviate them by using wisely consts, references, or even pointers, and define sensible copy constructors.

Access member variables directly or pass as parameter?

I noticed that even when paying respect to the single responsibility principle of OOD, sometimes classes still grow large. Sometimes accessing member variables directly in methods feels like having global state, and a lot of stuff exists in the current scope. Just by looking at the method currently working in, it is not possible anymore to determine where invidiual variables accessible in the current scope come from.
When working together with a friend lately, I realized I write much more verbose code than him, because I pass member variables still as parameters into every single method.
Is this bad practice?
edit: example:
class AddNumbers {
public:
int a, b;
// ...
int addNumbers {
// I could have called this without arguments like this:
// return internalAlgorithmAddNumbers();
// because the data needed to compute the result is in members.
return internalAlgorithmAddNumbers(a,b);
}
private:
int internalAlgorithmAddNumbers(int sum1, int sum2) { return sum1+sum2; }
};
If a class has member variables, use them. If you want to pass parameters explicitly, make it a free function. Passing member variables around not only makes the code more verbose, it also violates people's expectations and makes the code hard to understand.
The entire purpose of a class is to create a set of functions with an implicitly passed shared state. If this isn't what you want to do, don't use a class.
Yes, definetely a bad practice.
Passing a member variable to a member function has no sense at all, from my point of view.
It has several disadvantages:
Decrease code readability
Cost in term of performances to copy the parameter on the stack
Eventually converting the method to a simple function, may have sense. In fact, from a performance point of view, call to non-member function are actually faster (doesn't need to dereference this pointer).
EDIT:
Answer to your comment. If the function can perform its job only using a few parameters passed explicitely, and doesn't need any internal state, than probably there is no reason to declare it has a member function. Use a simple C-style function call and pass the parameters to it.
I understand the problem, having had to maintain large classes in code I didn't originally author. In C++ we have the keyword const to help identify methods that don't change the state:
void methodA() const;
Use of this helps maintainability because we can see if a method may change the state of an object.
In other languages that don't have this concept I prefer to be clear about whether I'm changing the state of the instance variable by either having it passed in by reference or returning the change
this->mMemberVariable = this->someMethod();
Rather than
void someMethod()
{
this->mMemberVariable = 1; // change object state but do so in non transparent way
}
I have found over the years that this makes for easier to maintain code.

private object pointer vs object value, and returning object internals

Related to: C++ private pointer "leaking"?
According to Effective C++ (Item 28), "avoid returning handles (references, pointers, or iterators) to object internals. It increases encapsulation, helps const member functions act const, and minimizes the creation of dangling handles."
Returning objects by value is the only way I can think of to avoid returning handles. This to me suggests I should return private object internals by value as much as possible.
However, to return object by value, this requires the copy constructor which goes against the Google C++ Style Guide of "DISALLOW_COPY_AND_ASSIGN" operators.
As a C++ newbie, unless I am missing something, I find these two suggestions to conflict each other.
So my questions are: is there no silver bullet which allows efficient reference returns to object internals that aren't susceptible to dangling pointers? Is the const reference return as good as it gets? In addition, should I not be using pointers for private object fields that often? What is a general rule of thumb for choosing when to store private instance fields of objects as by value or by pointer?
(Edit) For clarification, Meyers' example dangling pointer code:
class Rectangle {
public:
const Point& upperLeft() const { return pData->ulhc; }
const Point& lowerRight() const { return pData->lrhc; }
...
};
class GUIObject { ... };
const Rectangle boundingBox(const GUIObject& obj);
If the client creates a function with code such as:
GUIObject *pgo; // point to some GUIObject
const Point *pUpperLeft = &(boundingBox(*pgo).upperLeft());
"The call to boundingBox will return a new, temporary Rectangle object [(called temp from here.)] upperLeft will then be called on temp, and that call will return a reference to an internal part of temp, in particular, to one of the Points making it up...at the end of the statement, boundingBox's return value temp will be destroyed, and that will indirectly lead to the destruction of temp's Points. That, in turn, will leave pUpperLeft pointing to an object that no longer exists." Meyers, Effective C++ (Item 28)
I think he is suggesting to return Point by value instead to avoid this:
const Point upperLeft() const { return pData->ulhc; }
The Google C++ style guide is, shall we say, somewhat "special" and has led to much discussion on various C++ newsgroups. Let's leave it at that.
Under normal circumstances I would suggest that following the guidelines in Effective C++ is generally considered to be a good thing; in your specific case, returning an object instead of any sort of reference to an internal object is usually the right thing to do. Most compilers are pretty good at handling large return values (Google for Return Value Optimization, pretty much every compiler does it).
If measurements with a profiler suggest that returning a value is becoming a bottleneck, then I would look at alternative methods.
First, let's look at this statement in context:
According to Effective C++ (Item 28),
"avoid returning handles (references,
pointers, or iterators) to object
internals. It increases encapsulation,
helps const member functions act
const, and minimizes the creation of
dangling handles."
This is basically talking about a class's ability to maintain invariants (properties that remain unchanged, roughly speaking).
Let's say you have a button widget wrapper, Button, which stores an OS-specific window handle to the button. If the client using the class had access to the internal handle, they could tamper with it using OS-specific calls like destroying the button, making it invisible, etc. Basically by returning this handle, your Button class sacrifices any control it originally had over the button handle.
You want to avoid these situations in such a Button class by providing everything you can do with the button as methods in this Button class. Then you don't need to ever return a handle to the OS-specific button handle.
Unfortunately, this doesn't always work in practice. Sometimes you have to return the handle or pointer or some other internal by reference for various reasons. Let's take boost::scoped_ptr, for instance. It is a smart pointer designed to manage memory through the internal pointer it stores. It has a get() method which returns this internal pointer. Unfortunately, that allows clients to do things like:
delete my_scoped_ptr.get(); // wrong
Nevertheless, this compromise was required because there are many cases where we are working with C/C++ APIs that require regular pointers to be passed in. Compromises are often necessary to satisfy libraries which don't accept your particular class but does accept one of its internals.
In your case, try to think if your class can avoid returning internals this way by instead providing functions to do everything one would want to do with the internal through your public interface. If not, then you've done all you can do; you'll have to return a pointer/reference to it but it would be a good habit to document it as a special case. You should also consider using friends if you know which places need to gain access to the class's internals in advance; this way you can keep such accessor methods private and inaccessible to everyone else.
Returning objects by value is the only
way I can think of to avoid returning
handles. This to me suggests I should
return private object internals by
value as much as possible.
No, if you can return a copy, then you can equally return by const reference. The clients cannot (under normal circumstances) tamper with such internals.
It really depends on the situation. If you plan to see changes in the calling method you want to pass by reference. Remember that passing by value is a pretty heavy operation. It requires a call to the copy constructor which in essence has to allocate and store enough memory to fit size of your object.
One thing you can do is fake pass by value. What that means is pass the actual parameter by value to a method that accepts const your object. This of course means the caller does not care to see changes to your object.
Try to limit pass by value if you can unless you have to.

Coding practices in C++, what is your pick and why?

I have a big object say MyApplicationContext which keeps information about MyApplication such as name, path, loginInformation, description, details and others..
//MyApplicationCtx
class MyApplicationCtx{
// ....
private:
std::string name;
std::string path;
std::string desciption;
struct loginInformation loginInfo;
int appVersion;
std::string appPresident;
//others
}
this is my method cloneApplication() which actually sets up a new application. there are two ways to do it as shown in Code 1 and Code 2. Which one should I prefer and why?
//Code 1
public void cloneApplication(MyApplicationCtx appObj){
setAppName(appObj);
setAppPath(appObj);
setAppAddress(&appObj); // Note this address is passed
setAppDescription(appObj);
setAppLoginInformation(appObj);
setAppVersion(appObj);
setAppPresident(appObj);
}
public void setAppLoginInformation(MyApplicationCtx appObj){
this->loginInfo = appObj.loginInfo; //assume it is correct
}
public void setAppAddress(MyApplicationCtx *appObj){
this->address = appObj->address;
}
.... // same way other setAppXXX(appObj) methods are called.
Q1. Does passing the big object appObj everytime has a performance impact?
Q2. If I pass it using reference, what should be the impact on performance?
public void setAppLoginInformation(MyApplicationCtx &appObj){
this->loginInfo = appObj.loginInfo;
}
//Code 2
public void setUpApplication(MyApplicationCtx appObj){
std::string appName;
appName += appOj.getName();
appName += "myname";
setAppName(appName);
std::string appPath;
appPath += appObj.getPath();
appPath += "myname";
setAppPath(appPath);
std::string appaddress;
appaddress += appObj.getAppAddress();
appaddress += "myname";
setAppAddress(appaddress);
... same way setup the string for description and pass it to function
setAppDescription(appdescription);
struct loginInformation loginInfo = appObj.getLoginInfo();
setAppLoginInformation(loginInfo);
... similarly appVersion
setAppVersion(appVersion);
... similarly appPresident
setAppPresident(appPresident);
}
Q3. Compare code 1 and code 2, which one should I use? Personally i like Code 1
You're better off defining a Copy Constructor and an Assignment Operator:
// Note the use of passing by const reference! This avoids the overhead of copying the object in the function call.
MyApplicationCtx(const MyApplicationCtx& other);
MyApplicationCtx& operator = (const MyApplicationCtx& other);
Better still, also define a private struct in your class that looks like:
struct AppInfo
{
std::string name;
std::string path;
std::string desciption;
struct loginInformation loginInfo;
int appVersion;
std::string appPresident;
};
In your App class' copy constructor and assignment operator you can take advantage of AppInfo's automatically generated assignment operator to do all of the assignment for you. This is assuming you only want a subset of MyApplicationCtx's members copied when you "clone".
This will also automatically be correct if you add or remove members of the AppInfo struct without having to go and change all of your boilerplate.
Short answer:
Q1: Given the size of your MyAppCtx class, yes, a significant performance hit will take place if the data is dealt with very frequently.
Q2: Minimal, you're passing a pointer.
Q3: Neither, for large objects like that you should use reference semantics and access the data through accessors. Don't worry about function call overhead, with optimizations turned on, the compiler can inline them if they meet various criteria (which I leave up to you to find out).
Long answer:
Given functions:
void FuncByValue(MyAppCtx ctx);
void FuncByRef1(MyAppCtx& ctx);
void FuncByRef2(MyAppCtx* ctx);
When passing large objects like your MyApplicationCtx, it's a good idea to use reference semantics (FuncByRef1 & FuncByRef2), passing by reference is identical in performance to passing a pointer, the difference is only the syntax. If you pass the object by value, the object is copy-constructed into the function, such that the argument you pass into FuncByValue is different from the parameter FuncByValue receives. This is where you have to be careful of pointers (if any) contained in an object that was passed by value, because the pointer will have been copied as well, so it's very possible that more than one object will point to one element in memory at a given time, which could lead to memory leaks, corruption, etc.
In general, for objects like your MyAppCtx, I would recommend passing by reference and using accessors as appropriate.
Note, the reason I differentiated between argument and parameter above is that there is a difference between a function argument and a function parameter, it is as follows:
Given (template T is used simply to demonstrate that object type is irrelevent here):
template<typename T>
void MyFunc(T myTobject);
When calling MyFunc, you pass in an argument, eg:
int my_arg = 3;
MyFunc(my_arg);
And MyFunc receives a parameter, eg:
template<typename T>
void MyFunc(T myTobject)
{
T cloned_param = T(myTobject);
}
In other words, my_arg is an argument, myTobject is a parameter.
Another note, in the above examples, there are essentially three versions of my_arg in memory: the original argument, the copy-constructed parameter myTobject, plus cloned_param which was explicitly copied as well.
Luke beat me to tell you about copy constructors, to answer your other questions passing a large object by value has a performance impact when compared to passing by reference, make it a const if the function won't change it as in this case.
General:
Why do you need to copy application object? Isn't it better to use singleton for this (with completely disabled copying by the way)?
Q1:
Not only performance (yes, they will be copied) but memory too. As soon as I saw std::string implementations they at least occupy 2 memory chunks and first is in any case significantly less then minimal allocation size so such objects could cause memory efficiency problem if cloned extensively.
Q2:
Passing reference is barely different (from performance point of view) from passing pointer so this should in general constant complexity. It is much better. Don't forget to add "const" modifier to block modifications.
Q3:
I don't like actually both because of encapsulation broken. Once I saw good Java programmer article called something like "Why setters/getters are evil" (Well, I found it easily, there is not so much based on Java itself). This is VERY useful article to change style forever.
Q1..
Pass by object is heavy operation since it will create copy by invoking copy constructor.
Q2.
Pass reference to constant , it will improve perfomance.
Q1 - yes, every time you pass an object a copy is done
Q2 - minimal since an object passed by reference is basically just a pointer
Q3 - It is generally not a good idea to have large monolithic objects, instead you should split your objects into smaller objects, this allows for better re-usability and makes the code easier to read.
The best practice for cloning an object where all the members are copyable, like "Code 1" appears to be doing, is to use the default copy constructor - you don't have to write any code at all. Just copy like this:
MyApplicationCtx new_app = old_app;
"Code 2" is doing something different to "Code 1", so choosing one over the other is a matter of what you want the code to do, not a matter of style.
Q1. Passing a large object by value will cause it to be copied, which will have an impact on performance.
Q2. Yes, passing a reference to a large structure is more efficient than passing a copy. The only way to tell how large the impact is is to measure it with a profiler.
There is one single point that has not been dealt in any other of the answers (that focused on your explicit questions more than in the general approach). I agree with #luke in that you should use what is idiomatic: copy constructor and assignment operators are there for a reason. But just for the sake of discusion on the first possibility you presented:
In the first block you propose small functions like:
public:
void setAppLoginInformation(MyApplicationCtx appObj){
this->loginInfo = appObj.loginInfo; //assume it is correct
}
Now, besides the fact that the parameter should be passed by const reference, there are some other design issues there. You are offering a public operation that promises to change the login information, but the argument you require from your user is a full blown application context.
If you want to provide a method for just setting one of the attributes, I would change the method signature to match the attribute type:
public:
void setAppLoginInformation( loginInformation const & li ); // struct is optional here
This offers the possibility of changing the loginInformation both with a full application context or just with some specific login information object you can build yourself.
If on the other hand you want to disallow changing particular attributes of your class and you want to allow setting the values only from another application context object, then you should use the assignment operator, and if you want to do it in terms of small setter functions (assuming that the compiler provided assigment operator does not suffice), make them private.
With the proposed design you are offering users the possibility of setting each attribute to any value, but you are doing so in a cumbersome, hard to use way.