Hello,

I am having trouble in using the data member of class 1 in the member function of another class 2. Following is my code.

class a {
public:
     a();  
    ~a();

     std::vector<int> temp;    
};

class b {
public:
      b();
      ~b();
      int test();
}

b::b()
{
      a *a1;
      a1 = new a();
}

b::test()
{
      a *a2;
      a2->temp.size();              // Error here. 
}

int main()
{
     b *b1;
     b1 = new b();
     return 0;
}

I am creating a new pointer for the class 'a' inside the function of another class 'b'. Is that wrong. What would be the right way to do so.

Any help is really appreciated.

Thanks

Edited 7 Years Ago by guest7: n/a

I fixed up your code and added some comments tell me if I changed it from what you were wanting to do.

#include <vector>
#include <iostream>

using namespace std;

class A
{
	public:
	A(){};
	~A();
	
	std::vector<int> temp; //not sure how big your program is or how advanced you are but I hate using std:: I just use the namespace for small stuff
};

class B
{
	public:
	A *a1; //declare here
	B();
	~B();
	int test();
};

B::B()
{
	a1 = new A; //define here
	a1->temp.push_back(5); //put a value to the vectore for testing length
}

int B::test() //didn't have return type int like function prototype has
{
	return a1->temp.size(); //you wern't returning anything either
}

int main()
{
	B *b = new B;
     
	cout << b->test() << endl;
     
	system("PAUSE");
	return 0;
}

Edited 7 Years Ago by sfuo: fixed indents from copy pasted code

This article has been dead for over six months. Start a new discussion instead.