Click here to Skip to main content
12,632,959 members (32,509 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C++
Hi all,
There are two classes class1 and class2

class1()
{
public: 
CV3 Value1;
}

class2()
{
//how to access the variable Value1 here?
}



class1* temp;
temp->variable.x; 
//this gives initialisation error;
Posted 18-Jul-12 3:03am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

//this gives initialisation error;

of course it does. you haven't actually created an instance of an object of type class1. you created a pointer to an object, and they you didn't point it to anything.

try this:
class1 temp;
temp.variable.x; 


or this:
class1 *temp = new class1;
temp->variable.x; 
  Permalink  
Comments
Member 8446342 18-Jul-12 8:36am
   
Thanks, was being a lil silly :P
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

A possible variant :) :
class A
{
  int m_iVar;
public:
  A(int iVar) : m_iVar(iVar) {}
  int GetVar() const { return m_iVar; }
};

class B
{
  A* m_pcA;
public:
  B(A* pcA) : m_pcA(pcA) { ASSERT(m_pcA); }
  int Test() const { return m_pcA ? m_pcA->GetVar() : 0; }
}

void Tast()
{
  enum { testVar = 3 };
  A a(testVar);
  B b(&a);
  int iResult(b.Test());
  ASSERT(testVar == iResult);
}
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

Why doing all? just inherit class A as parent to class B. so you can access class A public variable using class B object
  Permalink  
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 4

Also u can make class2 as a friend class of class1 to access members of it.
  Permalink  
Comments
Albert Holguin 19-Jul-12 10:51am
   
This is only applicable to accessing private members. You also need to already have the object instantiated somehow.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.161208.2 | Last Updated 19 Jul 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100