Initialize private access variable [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 8 years ago.
Improve this question
InC++, is it valid to initialize a private access variable outside of the class definition like this?
class Test
{
private: int a;
public: int b;
}
int Test::a = 1;

The example in your question is not valid. If the member variable is static you can initialize it like you do in your example. If the member variable is not static you should initialize in in either the constructor or class definition.
It also does not matter what the access privilege is and the variables are initialized the same way regardless if they are public, protected, or private .
struct Foo
{
Foo() : a{1} // ctor-initializer
{
b = 2; // ctor body
}
int a;
int b;
int c = 3; // At definition.
};

"is it valid to initialize a private access variable ... like this?"
No. If you want to initialize that variable for each instance of Test, do it in a constructor.
class Test
{
Test() : a{1} {}
private: int a;
public: int b;
}

If you want all the instances of your class Test share the variable a, you can make it static. Il you do, you can initialize it like you said.

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;
}

Design of c++ class: common use of class members in other class members; Small interface vs small classes [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 6 years ago.
Improve this question
Say I have a class A with some member attributes. A also has a vector with objects of class B (std::vector<B>). Those B objects need some (let's say 5) of the attributes of A. I see two ways of handling this:
1) Let B have references to those attributes, and assign them in B's constructor.
2) Let B only have a reference to the A object, and get the attributes via public getAttributeXYZ() functions.
I can see that solution 1) technically knows less about A, therefore it's better because it couldn't for example call some wrong A function. But I feel like 2) is much cleaner, since the constructor is way smaller and the B class has much fewer (reference-) attributes itself. Is there a general better way or does it depend on the details?
Context: In my program, those members of A are classes for texture management, text drawing etc that can be shared by all of the B objects.
In this case, you can have your cake and eat it too, by giving the Bs access to only the relevant subset of A. There are multiple ways you could go about this.
One, gather the attributes in a dedicated class:
struct A
{
struct SharedData
{
int data;
// ...
};
A();
private:
SharedData sharedData;
std::vector<B> bs;
// other data here
};
struct B
{
B(A::SharedData *data) : data{data} {}
private:
A::SharedData *data;
};
A::A() : bs{B{&sharedData}} {}
Two, give A a dedicated interface to access these attributes:
struct SharedDataInterface
{
virtual int getData() const = 0;
};
struct A : SharedDataInterface
{
int getData() override { return sharedData; }
A();
private:
std::vector<B> bs;
int sharedData;
// other data here
};
struct B
{
B(SharedDataInterface *data) : data{data} {}
private:
SharedDataInterface *data;
};
A::A() : bs{B{this}} {}
I'm sure other variations on this topic are also possible.

Accessing private data members using friend 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 8 years ago.
Improve this question
I learnt that declaring a class as a friend class enables it to use the contents or members of the class in which it is declared. I used the following code:
#include <iostream>
using namespace std;
class two; // forward class declaration
class one {
private:
friend class two; // friend class declared
int a; // to be accessed later
public:
one() { a = 5; }
};
class two {
private:
int b;
public:
two() {
b = a; // intended to access 'a' and assign to 'b'
cout << " " << b << endl;
}
};
int main() {
one one_obj;
two two_obj;
return 0;
}
Error is: 'a' was not declared in this scope
What I've noticed in most examples of friend class is that constructor 'two()' will use 'class one' as the argument and later use the data member 'a'. But I wouldn't always want to make a new object as an argument to constructor two(). For example, calling constructor one() has already been done and the value of 'a' has already been set. Making a new object would mean doing that again, which might not be favorable. So what it all leads to is that, can I access members of class using friend class but without having to declare an object once again?
Class two being a friend of class one only overrides the access checking.
It still means you must actually refer to a static member of the class, or a non-static member of a specific instance of the class the normal way.
You might profit from choosing a tutorial or book from The definitive C++ book list, and reading up about it all.
b = a; // intended to access 'a' and assign to 'b'
Just because it is friend you cannot directly access it's members. You need to create one object to access it's members.
one o;
b = o.a; //now it should work

Pass Object to Class via Constructor [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Why does this code not work:
int main () {
Bob bob;
bob.giveANewFredSomeData();
Fred::sharedFred.getANumber(); //Crashes here due to someData inside fred being NULL
return 0;
}
Class Data {
int aNumber;
}
Class Bob {
void giveANewFredSomeData{
Data data;
Fred::sharedFred = new Fred(data);
}
}
Class Fred {
Data someData;
static sharedFred;
Fred (Data data) {
someData = data;
}
int getANumber(){
return someData.aNumber
}
}
Your code is not working because:
You need a semicolon after the declaration of a class
static is not a valid type
static objects have to be initialized outside of their definition in the class in order to be used elsewhere in the code. You need something like: Fred Fred::sharedFred; before main
Declaration of a function must have () in front of the function name before the {} braces
the classes have to be in the scope of main function for them to be used, and also in the scope of each other depending on what is calling what. i.e. main has to be declared after the class and same for each class that calls another
Properties/methods declared in a class are private by default. To make group of properties/methods public, have the keyword public followed by a colon at the top of the group