Access an object from another file.
Hi all,
I am new to Linux and c++ programming.
What I am trying to do is to declare an object in a .cpp and be able to access it from main.At the moment my code creates a new object in the ena.cpp and cannot use the one from the alpha.cpp. How can i access the object from alpha.cpp (bita.dio=6) from the main (ena.cpp).
Many thanks in advance.
ena.cpp
Code:
#include <iostream>
#include "alpha.h"
#include "bita.h"
using namespace std;
int main()
{
A ob(4);
B bita;//<this creates a new project which is irrelevant of the one i need to pass from alpha.cpp
// i need to remove that
cout << ob.get_a();
cout << bita.dio;//<-- This currently outputs 2 (and not 6 as i want)
//cout << par;
return 0;
}
alpha.cpp
Code:
#include "alpha.h"
#include "bita.h"
A::A(int x)
{
B bita;
a = bita.ena;
bita.dio = 6;//<---------- i want this to be accesible by ena.cpp directly
}
int A::get_a()
{
return a;
}
alpha.h
Code:
#include "bita.h"
#ifndef ALPHA_H
#define ALPHA_H
class A {
int a;
public:
A(int x);
int get_a();
};
#endif /*ALPHA_H_*/
bita.h
Code:
#include "bita.h"
#ifndef ALPHA_H
#define ALPHA_H
class A {
int a;
public:
A(int x);
int get_a();
};
#endif /*ALPHA_H_*/
bita.cpp
Code:
#include "bita.h"
B::B(){
ena = 1;
dio = 2;
tria = 3;
}
Re: Access an object from another file.
Quote:
Originally Posted by
cbarmpar
How can i access the object from alpha.cpp (bita.dio=6) from the main (ena.cpp).
alpha.cpp
Code:
#include "alpha.h"
#include "bita.h"
A::A(int x)
{
B bita;
a = bita.ena;
bita.dio = 6;//<---------- i want this to be accesible by ena.cpp directly
}
You cannot because 'bita' is created locally in 'A' constructor. When 'A' constructor finishes it's job then 'bita' is destroyed. You can add your own destructor to 'B' which will print something and see yourself.
You have to made 'bita' a member of 'A' class:
Code:
class A {
B bita;
int a;
public:
A(int x);
int get_a();
B * get_bita();
};
A::A(int x) {
bita.dio = 6;
}
B * A::get_bita() {
return &bita;
}
int main() {
A ob(4);
cout << ob.get_bita()->dio; // will print 6
}