Class Access Variable - c++

I've written out a template of what the basic code I'm trying to figure out is based on so you don't need to sift through it
#include <iostream>
using namespace std;
class class1 {
int main()
{
return 0;
}

If you need to do it the the exact declaration order in your post you can do this with a forward declaration. This will allow you to declare accessclass2 to take an instance of class2 as an argument without knowing the details. You will simply need to define accessclass2 after class2 has been defined.
#include <iostream>
using namespace std;
// Forward declaration allows you to pass a reference to the function withing
// having the details of the class2 yet.
class class2;
class class1
{
public:
int x;
class1()
{
x = 0;
}
void accessclass2(class2& other);
};
class class2 {
public:
int y;
class2()
{
y = 10;
}
void print()
{
cout << y << endl;
}
};
void class1::accessclass2(class2& other)
{
other.print();
}
int main()
{
class1 foo;
class2 bar;
foo.accessclass2(bar);
return 0;
}

Related

Can i make a define constructor which contains an object from another class?

Can I do an defined constructor which contains an object from another class?
If i can do how is defined.
this is an example.I do classes and how could be defined the constructor of class "Abonati" which contains an object "abonament"
I need that because i have another class which contain a vector of "abonati"
#pragma once
#include"abonament.h"
#include<iostream>
#include<vector>
using namespace std;
class abonati
{
char*nume_abonat;
int nr_telefon;
char *numefisier;
abonament *a;
public:
abonati();
abonati(char*, int , char *,abonament *);
abonati(abonati&a);
void Send();
~abonati();
};
`#pragma once
#include"abonati.h"
class abonament
{
protected:
int cost;
public:
abonament();
abonament(int costa);
virtual ~abonament();
};
#include "abonament.h"
abonament::abonament()
{
this->cost = 0;
}
abonament::abonament(int costa)
{
this->cost = costa;
}
abonament::~abonament()
{
}
`
I guess you would like to pass an class instance to another class constructor
Here is an example
#include <iostream>
class A
{
public:
A(int value) : m_int(value) {}
int GetInt() { return m_int; }
private:
int m_int;
};
class B
{
public:
B(A& a) : m_int(a.GetInt()) {} // Here constructor expects instance of class A
int GetInt() { return m_int; }
private:
int m_int;
};
int main()
{
A a(2);
B b(a); // Pass an object of class A to constructor of class B
std::cout << b.GetInt() << std::endl;
return 0;
}
Prints
2

How to call another class's function from a class WITHOUT INHERITANCE [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
so for one of the questions in our assignment, our prof gave us this following code snippet and asked us to make it run and implement it so that we are able to access class2's print() function from class1.
However, we are required to do this without the use of any inheritance/aggregation/composition between the two classes, which I am having trouble with. Aside from that, we are able to modify anything to make the code runnable. Thanks to anyone able to help!
#include <iostream>
using namespace std;
class class1 {
public:
int x;
class1()
{
x = 0;
}
void accessclass2(/* to be implemented*/)
{
//call the print() function from class2
}
};
class class2 {
public:
int y;
class2()
{
y = 10;
}
void print()
{
cout << y << endl;
}
};
int main()
{ //to be implemented;
//create class1 and class2 objects and access the print() function
return 0;
}
If you separate these into .hpp and .cpp files, then you can forward declare class2 and pass by pointer to accessclass2.
class1.hpp:
...
class class2;// forward declaration
...
class class1
{
...
void accessclass2(class2 *x);
...
};
class1.cpp:
...
void class1::accessclass2(class2 *x)
{
x->print();
}
...
#include <iostream>
using namespace std;
class class2 {
public:
int y;
class2()
{
y = 10;
}
void print() const
{
cout << y << endl;
}
};
class class1 {
public:
int x;
class1()
{
x = 0;
}
void accessclass2(const class2 & cl2)
{
cl2.print();
}
};
int main()
{
class2 c2 = class2();
class1 c1 = class1();
c1.accessclass2(c2);
return 0;
}
more secure method would be to make print() as a constant function: void print() const {}
and passing c2 as const reference as
void accessclass2(const class2 & cl2)`
How about:
int main()
{
//create class1 and class2 objects and access the print() function
class2 c2Object;
C2Object.print();
// Oh, you want to use class2::print() from within class1? Ok:
class1 c1Object;
c1Object.accessclass2(&c2Object);
}
// In class2's implementation:
void accessclass2(class2 *pClass2Object)
{
//call the print() function from class2
pClass2Object->print();
}

Accessibility of C++ vector in derived class from base class

My scenario is simplified in the following example:
#include <iostream>
#include <vector>
using namespace std;
class C;
class A
{
protected:
C * cPointer;
A();
virtual void updateList() = 0;
void callFunc();
};
class B : public A
{
private:
vector<int> list;
void updateList();
public:
void callFromA();
};
class C
{
friend class A;
friend class B; // I want to get rid off this declaration
private:
int sum;
void set_sum( int val );
public:
static C * getCPointer();
};
A::A()
{
cPointer = C::getCPointer();
}
void A::callFunc()
{
updateList();
}
void B::updateList()
{
list.push_back(2);
list.push_back(4);
int s = 0;
for( unsigned int i=0; i<list.size(); i++ )
{
s += list[i];
}
cPointer->set_sum(s);
}
void B::callFromA()
{
callFunc();
}
void C::set_sum( int val )
{
sum = val;
cout << "Sum at C is: " << sum << endl;
}
C * C::getCPointer()
{
static C cPointer;
return & cPointer;
}
int main( int argc, char ** argv)
{
B b;
b.callFromA();
return 0;
}
This example works fine. But I want to get rid of the "friend class B" declaration in class C and achieving similar functionality. Actually I want to have either of the following:
accessibility of C::set_sum() from B::updateList() which will not be possible without the "friend class B" declaration in class C.
accessibility of B::list in A::callFunc() whereby I can push the logic from B::updateList to A::callFunc() which basically means ability to access a list in the derived class from the base class. In this way, I will be able to access the set_sum() in A::callFunc() due to "friend class A" declaration in class C.
Any idea to achieve this without involving major design changes is desirable!
Thanks!
I'm not sure if I understand all your restrictions, but maybe this works better for you. Basically, you can access B::list from A using a virtual function. I've commented the changes in the code.
#include <iostream>
#include <vector>
using namespace std;
class A;
class C
{
friend class A;
private:
int sum;
void set_sum(int val);
public:
static C * getCPointer();
};
class A
{
protected:
C * cPointer;
A();
virtual int getS() = 0; // virtual function to calculate data from vector in derived class B
virtual void updateList()
{
cPointer->set_sum(getS()); // A is friend of C, so you can access B data from A
}
void callFunc();
};
class B : public A
{
private:
vector<int> list;
void updateList();
int getS() // concrete implementation to access vector data
{
int s = 0;
for (unsigned int i = 0; i < list.size(); i++)
{
s += list[i];
}
return s;
}
public:
void callFromA();
};
A::A()
{
cPointer = C::getCPointer();
}
void A::callFunc()
{
updateList();
}
void B::updateList()
{
list.push_back(2);
list.push_back(4);
A::updateList(); // Call to super implementation
}
void B::callFromA()
{
callFunc();
}
void C::set_sum(int val)
{
sum = val;
cout << "Sum at C is: " << sum << endl;
}
C * C::getCPointer()
{
static C cPointer;
return &cPointer;
}
int main(int argc, char ** argv)
{
B b;
b.callFromA();
return 0;
}
You can not access members of derived classes inside the base class, period. The object at hand might be of the base class, or even of a completely unrelated derived class, with guaranteed "interesting" consecuences. Any design asking for doing so is seriously broken, and needs rethinking.
You can make the member function of the base class which wants to do so virtual, and redefine it in the derived class to do whatever perversion you have in mind. Meanwhile, the chaste member of the base class can just refuse if called, signalling the mistake in a sane way. That way you get a guarantee that nothing too untoward can happen.

Shared variable among classes c++

I have multiple classes that need to share a single instance of another class. Publicly it should be unknown that this class exists. Is it appropriate to do something like the following? (Was tested as written)
#include <iostream>
class hideme
{
private:
int a;
public:
void set(int b) { a = b; }
void add(int b) { a += b; }
int get() { return a; }
hideme() : a(0) { }
};
class HiddenWrapper
{
protected:
static hideme A;
};
hideme HiddenWrapper::A;
class addOne : public HiddenWrapper
{
public:
void add() { A.add(1); }
int get() { return A.get(); }
};
class addTwo : public HiddenWrapper
{
public:
void add() { A.add(2); }
int get() { return A.get(); }
};
int main()
{
addOne a;
addTwo b;
std::cout << "Initialized: " << a.get() << std::endl;
a.add();
std::cout << "Added one: " << a.get() << std::endl;
b.add();
std::cout << "Added two: " << b.get() << std::endl;
return 0;
}
For what it's worth, hideme is part of a library I'm attempting to design a facade around, and the other classes have members from the library that interact with the static hideme.
Additionally, if the header file written for HiddenWrapper has no corresponding source file, is that the best place to define its static member? With an include guard.
Is there any other method to solve this problem? As far as I could imagine (not terribly far) I could only solve it otherwise with friendship, which I am wary of.
You can prevent access to a class by not making it accessible outside the translation unit that uses it.
// public_header.h
class A {
void bar();
};
class B {
void foo();
}
// private_implementation.cpp
#include "public_header.h"
namespace {
class hidden { void baz() {} };
hidden h;
}
void A::bar() {
h.baz();
}
void B::foo() {
h.baz();
}
This class will be usable only by A::bar and B::foo. The type hidden and the variable h still technically have external linkage, but no other translation unit can say their names.
Sometimes it is a better idea to inject shared ressources (by reference or pointer) through the constructor (also known as composition instead of inheritance). This way gives you the ability to share or not (e.g. to have a thread-safe variant of your code which is not). See http://de.wikipedia.org/wiki/Inversion_of_Control principle for more info.
This implements a singleton around some other class and hides it from
users:
class hideme {};
// fwd declarations
class x;
// library internal
class S
{
S() = delete;
S(S const&) = delete;
void operator=(S const&) = delete;
private:
static hideme& getInstance()
{
static hideme instance;
return instance;
}
friend x;
};
// library classes
class x {
hideme& s;
public:
x() : s(S::getInstance()) {}
};
int main()
{
x x;
return 0;
}
This does not handle cases where you actually want the hideme
instance to be destroyed when no other object is using it anymore. For
that you need to get a little bit more inventive using reference
counting.
I also should say that I think this is a bad idea. Singletons almost
always are.
Generally, the best approach, if you have a variable in the main part, and want to share it with all classes.
For example, if class X makes a change on this var, the change happened to the var in the main as well: you can use EXTEND
************************ The main *********************
#include <iostream>
using namespace std;
#include "Game.hpp"
//0: not specified yet; 1:singlemode; 2:multiplayerMode
int playingMode = 0;
int main()
{
Game game;
game.Run();
std::cout<< playingMode << std::endl;
return 0;
}
*********************** Class X *****************
#include <iostream>
using namespace std;
extern int playingMode;
....
....
if(m_isSinglePressed)
{
playingMode = 1;
...
}
else if(m_isMultiPressed)
{
playingMode = 2;
...
}

c++ forward declaration

#include <iostream>
#include <cstring>
using namespace std;
class Obj;
class Test {
friend class Obj;
public:
Test()
{
}
~Test()
{
}
void foo()
{
//print();
//Obj::print();
//Obj x;
//x.print();
}
};
class Obj {
public:
void print()
{
cout << "print here" << endl;
}
};
int main()
{
Test test;
test.foo();
return 0;
}
Quick question,how can I call print the correct way in Test::foo() ?
You need to define the member function after the definition of Obj:
class Test {
public:
void foo();
};
class Obj {
public:
void print() { }
};
void Test::foo() {
Obj o;
o.print();
}
As mentioned by james you should define the member function after the definition of Obj. Also you are calling Obj::print, but print is not a static member function so you must call it on an instance of Obj not Obj itself.
If you really do want print to be a static member, declare it so.
class Obj {
public:
static void print(){ blah }
}
Also you do not need to make Obj a friend in order to access its public methods.
Also can OP please define "correct way", I was assuming you wanted it to be a static member function, james' answer is correct if you want one instance of Obj per instance of Test.
UPDATED
OP, as per your comment you must have the declaration of Obj along with print BEFORE using it within Test. This can be achieved in many ways:
move the entire class Obj defintion (and declaration) before Test
declare Obj's methods with its class definition and define them later.
declare Test like you have and Define Test as per James' post (after Obj).
The following works fine:
#include <iostream>
#include <cstring>
using namespace std;
class Obj {
public:
static void print()
{
cout << "print here" << endl;
}
};
class Test {
public:
Test()
{
}
~Test()
{
}
void foo()
{
Obj::print();
}
};
int main()
{
Test test;
test.foo();
return 0;
}
However it is always nicer (in my opinion) to separate declaration from definition for all but the most trivial of cases.