this program works but i know there HAS to be a better way
Nov 15, 2013 at 5:18pm UTC
Ideally i want some way to just give ClassTwo access to the variable inside of the class one object but im not sure how to do that. inheritance, as far as i understand it, would just cause the functions and variables to be inherited, it would not pass one the actual instance of that variable and friendship would force to me to change the structure of the program in relation to the way the classes are derived.
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include "ClassOne.h"
#include "ClassTwo.h"
#include <iostream>
int main()
{
ClassOne ClassOneObj;
ClassTwo ClassTwoObj[10000];
for (int i=0; i<10000; ++i)
{
ClassTwoObj[i].PassArrayAddress(ClassOneObj.GetArrayAddress());
}
ClassTwoObj[8472].Test();
return 0;
}
ClassOne.h
1 2 3 4 5 6 7 8 9
#include <iostream>
class ClassOne
{
public :
ClassOne();
int * GetArrayAddress();
int TestArray[2];
};
ClassOne.cpp
1 2 3 4 5 6 7 8 9 10 11 12
#include "ClassOne.h"
ClassOne::ClassOne()
{
TestArray[0]=3;
TestArray[1]=6;
}
int * ClassOne::GetArrayAddress()
{
return &TestArray[0];
}
ClassTwo.h
1 2 3 4 5 6 7 8 9
#include <iostream>
class ClassTwo
{
public :
void PassArrayAddress(int *);
void Test();
int * ArrayAddress;
};
ClassTwo.cpp
1 2 3 4 5 6 7 8 9 10 11
#include "ClassTwo.h"
void ClassTwo::PassArrayAddress(int * PassedAddress)
{
ArrayAddress=PassedAddress;
}
void ClassTwo::Test()
{
std::cout << ArrayAddress << std::endl;
}
Thanks to everyone who took a look!
Last edited on Nov 15, 2013 at 5:19pm UTC
Nov 15, 2013 at 8:46pm UTC
bump
Nov 15, 2013 at 11:13pm UTC
If I understand you correctly, you could make the "shared" member static.
class.h
1 2 3 4 5 6 7 8 9 10 11 12 13
#ifndef _CLASS_H_
#define _CLASS_H_
class ClassOne {
public :
static unsigned short foo;
ClassOne() {foo=0;}
};
class ClassTwo : public ClassOne {};
#endif
class.cpp
1 2 3
#include "class.h"
unsigned short ClassOne::foo = 0;
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include "class.h"
int main(int argc, char * argv[]) {
ClassOne one;
ClassTwo two;
std::cout << "One: " << one.foo << std::endl;
std::cout << "Two: " << two.foo << std::endl;
two.foo = 1;
std::cout << "One: " << one.foo << std::endl;
std::cout << "Two: " << two.foo << std::endl;
std::cin.get();
return 0;
}
Nov 15, 2013 at 11:32pm UTC
thanks ill experiment with it a bit and see if i can figure out whats going on here
*edit* this is exactly what i was looking for!
Last edited on Nov 16, 2013 at 12:16am UTC
Topic archived. No new replies allowed.