With or without 'this' in POO attribute class [duplicate] - c++

This question already has answers here:
When should I make explicit use of the `this` pointer?
(12 answers)
Closed 9 years ago.
I wonder if there is some reason or not to use this in a attribute class?
class Foo
{
private:
int m_foo;
public:
int getIntance() { return this->m_foo; }
}
Other than the fact its say that this is the current class, are there others reasons?

No, do not use it. In that particular case, it is not needed, and this is less typing :
int getIntance() { return m_foo; }
Less you write is better. Even for people reading you code (they'll have less to read)

this is less typing. It is not mandatory in this particular case. There is no reason to use this keyword unless if you want to pass the current instance of your object to a function for example.
You can simply write :
int getIntance() { return m_foo; }
It is weird to call a method getInstance to return an int. It is quite uncommon...

There's no reason to use this, except when, for example, you want something outside the class to point to your instance (let's say, you add your instance - this - to a list of pointers).
In your example, this is redundant, since m_foo could easily have been returned by return m_foo; without any problem.
However, this can only be used in non-static member functions, or else it won't compile.

Related

Can I use constant variables and simple or constant function in the same program? [duplicate]

This question already has answers here:
C++ : What is wrong with my class constructors ? (no default constructor exists &/or conflicting declaration)?
(2 answers)
Is it true that a default constructor is synthesized for every class that does not define one?
(6 answers)
What is a synthesized constructor?
(1 answer)
Closed 3 months ago.
constant variables and functions in the same program cpp
#include<bits/stdc++.h>
using namespace std;
class student
{
public:
const int roll;
const string name;
student (int r,string n)
:roll(r),name(n)
{
cout<<roll<<endl;
cout<<name<<endl;
}
void display()
{
cout<<"Disp\n";
}
};
int main()
{
student obj(2003081,"ismail");
student o; //ERROR
o.display();
return 0;
}
I can't understand, why the compiler shows "no matching function for call to 'student::student()' "?
Where is the problem and how can I overcome this?
When you write a class with a custom constructor (in your case, student (int r,string n), the compiler won't also generate a default constructor (i.e. one that doesn't expect any arguments, allowing student o; to compile). It probably wouldn't make sense to have a default constructor for your class, as you need to get values somehow to initialise the const member variables, as you do in your custom constructor. So, it's good that student o; is an error. That said, sometimes there are reasons to want a default-constructible type (for example, some container you want to use may insist on it). Then you have to get rid of the const members and have a way of setting them after the default constructor has run, which is a bit ugly!
You don't have a constructor without parameters, so you can't make an object without passing parameters. Overcome it, by either making a default constructor or not making an object without parameters.
The confusing part may be that you can make an object without parameters if you didn't make any constructor, but from the moment a constructor is made, the default constructor must also be made if needed. This can be done with:
student() : roll(0), name("");
Even though that probably doesn't make a lot of sense, so you're best in not using student o;.

Can the protected member access check be subverted using static_cast? [duplicate]

This question already has answers here:
Access to protected member through member-pointer: is it a hack?
(4 answers)
Closed 4 years ago.
Consider
class A {
protected:
int m;
};
class B : public A {
void foo(A& a) {
a.m = 42; // ill-formed
}
void bar(A& a) {
auto pm = &B::m;
auto pm2 = static_cast<int A::*>(pm);
a.*pm2 = 42; // is this ok?
}
};
Trying to access A::m directly is ill-formed according to [class.protected]. However, it appears that we can always (?) circumvent this using static_cast, which allows a derived-to-base cast with pointers to members. Or is this somehow UB?
[Coliru link showing that bar compiles]
Yes, you can circumvent the protected mechanism in this way by using static_cast.
I think this is not undefined behavior in this particular case.
By using the static_cast you tell the compiler two things:
You ask the compiler to convert the B pointer into an A pointer.
You tell the compiler that this is ok to do so.
For 1. the compiler applies very limited checks of whether this is okay or not, and for static_cast it allows to cast from derived to base and the other way round, and that is it. So the compiler is happy. Whether a variable or pointer is protected or public is not part of the variable or pointer type. Neither pm nor pm2 carry the protected information.
For 2. the compiler completely leaves it up to you to make the decision whether this is okay or not in your design. It is not undefined behavior. It may still not be a good idea. pm2 is just a pointer to an int in A. You can reset it to a pointer to a different int in A which is public.
The background is that access control in C++ is generally per-class, plus there are some extra rules around protected which try to provide some level of access control on a per instance basis, but this protection is not perfect as you have demonstrated in your interesting question.

returning an empty initializer list as default value for a function [duplicate]

This question already has answers here:
How to elegantly return an object that is default-initialized?
(5 answers)
Closed 7 years ago.
keeping with DRY, I want to avoid repeating the return type of a function returning a default value:
Foo bar()
{
return Foo{}; // shouldn't be necessary to respecify Foo here.
}
I tried a few things and ended up with this construct:
Foo bar()
{
return {};
}
which seems to be a return expression from list-initialization. Which I expect is equivalent to calling return Foo{{}}. My question is, is this a thing? because I haven't often seen it used and it feels like it would be pretty convenient.
Foo bar()
{
return {};
}
That is perfect, and succinct! It will work as long as the default constructor is not declared to be explicit.
However, if you have this:
explicit Foo(); //though practically it doesn't make much sense to me!
then return {}; wont work, and you have to write return Foo{}; instread.

C++ Function Returning Different Data Types [duplicate]

This question already has answers here:
How to return different classes from one function?
(13 answers)
Closed 8 years ago.
First, allow me to apologize if the title of this question is vague.
That said, I'm trying to write a function that will return any one of a number of data types (all defined by me) based on conditions within the function. In essence, what I'm trying to do is this:
{
A itemA;
B itemB;
C itemC;
...
Do some calculations
...
if (some condition)
return itemA;
else if (some other condition)
return itemB;
else
return itemC;
}
Of course, this example is a little contrived but I think that gets my point across.
The classes A, B, and C are all child classes of some other class S but I don't want to return S as data will be lost if I do that. Further, the functionality doesn't really change even if the return type does so overloading it seems foolish. So then, should this be a template function or is there something else I need to do?
Thanks,
If you return a pointer or reference to S, you will not have a splicing problem:
S* func()
{ ... }
Note that you must dynamically allocate the variables.

Checking if a pointer points to a particular class C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Finding the type of an object in C++
I have a question with checking pointers to see if they conform to a particular derived class and take necessary action.
Lets say I currently have 2 derived classes DerivedClass1 and DerivedClass2 and the base class BaseClass. I would like to check the following action.
Ptr<BaseClass> ptr;
if (ptr points to DerivedClass1)
{
action1
}
else
{
action2
}
How do I check for ptr points to a particular DerivedClass?
If you were to think a bit more object-orientedly, you would just make it a virtual method on the base class:
Ptr<BaseClass> ptr;
ptr->Action();
and have each class implement it as needed. I realize this isn't an actual answer, but it's an alternative way of accomplishing your goal which is often considered to be better, which is why I think it's worth mentioning.
If BaseClass is polymorphic (contains virtual functions), you can test:
if (dynamic_cast<DerivedClass1*>(ptr.get()))
But usually you should use dynamic dispatch as unwind suggests, possibly a Visitor pattern, for this sort of thing. Littering your code with dynamic_cast makes it hard to maintain. I use dynamic_cast almost NEVER.
if(dynamic_cast<DerivedClass1*>(ptr))
{
// Points to DerivedClass1
}
else if(dynamic_cast<DerivedClass2*>(ptr)
{
// Points to DerivedClass2
}