Value access in C++ - c++

HI,
I have two clases A and B,
Here A is inheriting B and now i want to access a variable in B from A, I included A header in B and tried to access but showing some error in QObject.
Is it possible to acces like this.. Please help

Not sure i get your Q correctly....
class A {
public:
int nValueA;
protected:
int nValueB;
private:
int nValueC;
};
class B : public A {
public:
B();
int x, y, z;
};
B::B():
x(nValueA), //-->OK
y(nValueB), //-->OK
z(nValueC) //-->error due to child can't inherit parent's private member
{}
void main(){
B object;
object.nValueA = 888; //--> valid
object.nValueB = 888; //--> error since protected member is not accessible
object.nValueC = 888; //--> error since private member is not accessible
}
Possible solution:
class A {
public:
int nValueA;
int nValueB;
int nValueC;
};

Is your member variable private? Then you cannot, declare it protected.

Related

Dont allow access to member variable directly within same class

I am not sure is my question is right or not? But let me still try to ask once.
I have a Class with have few member variables defined. As per OO concepts, every member function can access , all member variables of its class.
But I want these member variable to be accessed via specific methods (Lets say Getters) , even within same class member functions.
It there any way to do it?
class A {
public:
void func1();
void func2();
B getB();
private:
B b;
}
void A::func1() {
b.functionFromB(); // function uses member variable b directly
}
void A::func2() {
B b1=getB(); // function ask for B from a function and then uses it. // I need something like this... And ensure each function uses same way otherwise there should be warning...
b1.functionFromB();
}
Thanks,
Kailas
No, there is not. You can do it via encapsulation and inheritance like:
class shape
{
private:
int angles;
protected:
shape(int angles_):angles(angles_){};
int getAngles() const;
}
class square : private shape
{
public:
square():shape(4){}
void doSth()
{
\\ you can access angles only via getAngles();
}
}
Any private members of the class can be accessed from within the class, but not by users of the class. So it looks like you need private members and public methods that allow access to them.
class A
{
private:
int a;
public:
int getA() {return a;}
};
int main()
{
A inst;
int t;
inst.a =5; // error member a is private
t = inst.getA(); //OK
}
The concept extends fine to nested class declarations in case you only want to allow instance of a class to be created from another class; details here
As others have said - you have to add an additional layer.
If you want to give access to specific methods then you can use the friend keyword. E.g.
// Public.h
#pragma once
class Public
{
public:
Public();
int GetI() const;
float GetF() const;
private:
std::unique_ptr<Private> p_;
};
//Public.cpp
#include "Public.h"
Public::Public()
: p_(new Private)
{
}
int Public::GetI() const
{
return p_->i_;
}
float Public::GetF() const
{
return p_->f_;
}
// Private.h
#pragma once
class Private
{
friend int Public::GetI() const;
friend float Public::GetF() const;
int i_;
float f_;
};
Keep in mind that every friend method can access ALL private members.
If you really really want to limit which methods can access which members then you can wrap each member in a separate class/struct and make only the getter/setter of that member a friend of that class/struct but I would not recommend this approach.

C++ declaring a static object in a class

I'm trying to declare a static object of a class A that I wrote in a different class B, like this:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}
What I want to achieve is to get int x in B::start() to equal int x in class A (4).
I tried googling all this for the past hour and all I understood was that C++ doesn't allow static objects' declarations. Is that correct?
If so, here's my question. How can I get the same result? What are my available workarounds? Keeping in mind that the rest of my code depends on the functions in class B to be static.
Error
error LNK2001: unresolved external symbol "private: static class A B::obj1"
Thanks!
You should initialize static var, the code:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
A B::obj1; // init static var
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}
As thinkerou said, you need to include the declaration of the variable:
A B::obj1;
For normal, non-static member variables you don't need this step because the variables are declared behind the scenes as part of the constructor. These variables are then tied to the instance of the class you just constructed. But static variables are not tied to any instance of a class; they are shared by all instances of a class. So constructors can't properly deal with them.
C++ gets around this by making you manually declare (and optionally initialize) any static member variables. Depending on where they are declared, they typically get constructed before your main() function starts, so they are available for use immediately.

C++ inheritance: protected variables not available

I've got the following C++ code in XCode, giving two errors I cannot make sense of:
#include <iostream>
class Buch{
public:
Buch (long int nummer = 0, char autor[25] = (char*)"", int jahr = 0, bool ausgel = false);
long int getNr();
int getJahr();
protected:
long int __nummer;
char __autor[25];
int __jahr;
bool __ausgel;
void setAusl(bool x);
bool getAusl();
};
class FachBuch : Buch {
public:
void setSWort(int sw);
int getSWort();
protected:
char __fach[15];
int __swort;
};
class UBuch : Buch {
public:
void setAlter(int a);
int getAlter();
protected:
int __kateg;
char __land[15];
private:
int _ab_alter;
};
class Bildband : UBuch {
public:
Bildband(long int nummer = 0, char autor[25] = (char*)"", int jahr = 0, int kategorie = 0, char land[15] = (char*)"");
};
Buch::Buch (long int nummer, char autor[25], int jahr, bool ausgel) {
__nummer = nummer;
//_autor = autor;
__jahr = jahr;
__ausgel = ausgel;
}
long int Buch::getNr() {
return __nummer;
}
int Buch::getJahr() {
return __jahr;
}
void Buch::setAusl(bool x) {
__ausgel = x;
}
bool Buch::getAusl() {
return __ausgel;
}
void FachBuch::setSWort(int x) {
__swort = x;
}
int FachBuch::getSWort() {
return __swort;
}
void UBuch::setAlter(int x) {
_ab_alter = x;
}
int UBuch::getAlter() {
return _ab_alter;
}
Bildband::Bildband(long int nummer, char autor[25], int jahr, int kategorie, char land[15]) {
__nummer = nummer; // error message: Cannot cast 'Bildband' to its private base class 'Buch'
//Buch(nummer, autor, jahr, false); // error message: '__nummer' is a private member of 'Buch'
}
int main () {
Bildband Masuren(356780, (char*)"Kranz", 2010, 4, (char*)"Polen");
return 0;
}
I get the following errors:
main.cpp:92:5: Cannot cast 'Bildband' to its private base class 'Buch'
main.cpp:92:5: '__nummer' is a private member of 'Buch'
My knowledge of C++ is quite limited and I had no luck googling, probably mainly because I lack the necessary C++ basic knowledge.
Can anyone explain to me why these errors occur and what terms I need to look up to understand the problem?
Thanks in advance.
They are not available because UBuch inherits Buch privately. When defining a class, inheritance is private by default.
// These two lines mean the same thing:
class UBuch : Buch
class UBuch : private Buch
All members of Buch are inherited, but those visible to UBuch are inherited as private to UBuch.
This means that code external to UBuch has no access to any members of Buch on UBuch objects, nor can it convert pointers or references to UBuch objects to pointers or references to Buch.
This includes classes that derive UBuch.
class Bildband : UBuch
Even though Buch is in the inheritance chain, its members were inherited privately by UBuch, and so Bildband has no access to the members inherited from Buch.
To fix this, you should inherit Buch publicly (and you probably want all of your other classes to inherit publicly from their respective base classes, too):
class UBuch : public Buch
Also, note that identifiers containing two consecutive underscores are reserved by the environment, so all such identifiers in your code (__nummer, __autor, etc.) cause undefined behavior.
If you don't define an access-specifier, the compiler will default to private inheritance for classes. Simply prefix your UBuch class and Buch class with "public" like so:
// ...
class UBuch : public Buch {
// ...
class Bildband : public UBuch {
I assume "public" here, since I guess that you want to provide access to the methods like getNr / getJahr from users of BildBand as well.
./regards
Florian
EDIT: See comments below
The type of inheritance effects which members are inherited:
public inheritance means only public members are inherited.
protected inheritance means public members are inherited and protected members are inherited as protected as well.
private inheritance means public members are inherited and protected members are inherited as private.
Here you are inheriting privately by default.

why getting errors in c++ program?

I think I have coded everything correctly in this program but still getting errors.
The object si it says it's not accessible.
#include<conio.h>
#include<iostream.h>
class s_interest
{
int p,t;
float r;
s_interest(int a, int b, float c)
{
p=a;
r=b;
t=c;
}
void method()
{
int result=(float)(p*t*r)/100;
cout<<"Simple interest:"<<result;
}
};
void main()
{
int pr,ti;
float ra;
cout<<"\n Enter the principle, rate of interest and time to calculate Simple Interest:";
cin>>pr>>ti>>ra;
s_interest si(pr,ti,ra);
si.method();
}
When the compiler tells you that something is not accessible, it's talking about the public: vs. protected: vs. private: access control. By default, all members of a class are private:, so you cannot access any of them from main(), including the constructor and the method.
To make the constructor public, add a public: section to your class, and put the constructor and the method there:
class s_interest
{
int p,t;
float r;
public: // <<== Add this
s_interest(int a, int b, float c)
{
...
}
void method()
{
...
}
};
Default member access for a class is private (whereas the default for struct is public). You need to make the constructor and method() public:
class s_interest
{
int p,t; // private
float r; // also private
public: // everything that follows has public access
s_interest(int a, int b, float c) { .... }
void method() { ....}
};
Note also that void main() is not standard C++. The return type needs to be int, so you need
int main()
{
...
}
And finally, iostream.h is not a standard C++ header. You need to include <iostream> if you are using a standards compliant C++ implementation.
Following High Integrity C++ Coding Standard guidelines, always declare first public, then protected and private members. See Rule 3.1.1 of hicpp-manual-version-3-3.pdf
All the variables & functions in your class are private. This is the default when access is not specified with the private: , protected: and public: specifiers. I suggest you have a good read of a tutorial - google C++ classes.
also it is int main() and never void main()
The problem is due to access specifiers. By default class methods and data members are private. Make your data members private and methods public. so you can set the private data members value using public methods.
class{
private:
int a;
int b;
int c;
public:
void method();
void print_sum();
};

How access class variables in c++

Is it possible in c++ to access class variables in other classes without creating an object. I have tried to use static, but the other class doesnt recognize my variable.
I have 3 classes. In two of those the sae variables should be used. In the third class I am changing the values. Would be grateful if you could help. Maybe youve got an example.
class Myclass
{
public:
static int i;
};
int Myclass::i = 10;
class YourClass
{
public:
void doSomething()
{
Myclass::i = 10; //This is how you access static member variables
}
};
int main()
{
YourClass obj;
obj.doSomething();
return 0;
}
static is the right keyword here:
class A {
public:
static int i; // <-- this is a class variable
};
class B {
public:
void f() { A::i = 3; } // <-- this is how you access class variables
};
They only potential problem I can think of is that
You made the class variable protected or private, thus rendering it inaccessible from other code.
You forgot to specify the full scope of the class variable (with A:: in this example).
I think the Singleton Pattern would help, but I'm no big fan of it. A lot better design would be to have one class take ownership of the object, and pass references to this object to the other classes.
yes you can bro, try this
struct car{
string model;
string paint;
int price;
};
int main(){
// creates an object of the class car
car BMW;
// assign the values
bmw.model = "m sports";
bmw.paint ="red";
bmw.price = 24000;
}