You are here:

C++/Passing file pointer to a constructor

Advertisement


Question
#include <iostream.h>
int z[10];
char x[10];
FILE *f1;
class rama
{
      int *integer;
      float *cubes;
      int x;
      public:  
      rama (int y,int l,int m,int n,int p)
      {
         
         no(y,l,m,n,p);
      }
      void power(int);
      void check();
      void no(int y,int l,int m,int n,int p);
};

void rama::no(int y,int l,int m,int n,int p)
{
   int j;
   integer=(int *)malloc(4*sizeof(int));
   
   for(j=1;j<=4;j++)
    {
      integer[j]=(z[j]);
  
    }
   power(y);
   check();
}

void rama:: power(int x)
{
  int j;
  cubes=(float *)malloc(4*sizeof(float));
  for(j=1;j<=4;j++)
    {
      cubes[j]=integer[j]*integer[j]*integer[j];
   
    }
}

class derived: public rama
{
  public:
  derived (int,int,int,int) : rama(3,z[1],z[2],z[3],z[4])
  {}
  
  
};

void rama:: check()
{
  if((cubes[1]+cubes[2])==(cubes[3]+cubes[4]))
  cout<<"Ramanujan Numbers";
  else
  cout<<"Not Ramanujan Numbers";
 }
 
int main (int a,char *ar[] )
{
 int j;
if(a>2)
  {
    if(a!=5)
    {
    cout<<"Enter the correct input";
    exit(0);
    }
     for(j=1;j<=4;j++)
      {
         z[j]=atoi(ar[j]);
         printf("[%d]\n",z[j]);
       }
   derived d(z[1],z[2],z[3],z[4]);
  }
if(a<5)
  {
      if(a!=2)
       {
         cout<<"Enter the file name";
         exit(0);
       }
   if((f1=fopen(ar[1],"r"))==NULL)
   printf("Error:No such file");
   
   
  }
   
   
}
I want to overload the constructor of the derived class to accept numbers from command line and read the numbers from a file.
In the above program i want to take the file name
from command line and pass the file pointer and access the file from the constructor of the derived class.
I am programming on a amd athlon processor with 512 mb ram and on Linux Operating system

Answer
Hello,

How about passing the valid FILE pointer to the constructor as a parameter. Once in the function body of the constructor, you can use your standard fseek, fread, fwrite functions in the constructor.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.