473,699 Members | 2,579 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help a poor FORTRAN programmer with member functions?


Just a bit of background: I'm one of a group of FORTRAN programmers, looking
to switch to C++. We are trying to write a few simple examples to
demonstrate the power of the language to our manager, so he will send us all
on a conversion course.

One of many reasons is that our code is littered with examples of:

SUBROUTINE PRINT_ITEM(ITEM , ITEM_TYPE)
IF (ITEM_TYPE .EQ. SQUARE) THEN
CALL PRINT_SQUARE(IT EM)
ELSEIF (ITEM_TYPE .EQ. CIRCLE) THEN
CALL PRINT_CIRCLE(IT EM)
ELSEIF ...
(lots more item types)
ENDIF
END

(with apologies for sullying the group with FORTRAN code).

Obviously We need to find and modify all these blocks whenever we add a new
object type, or operation.

I want to write a C++ equivalent, using classes and member functions so that
I can print (or draw, or interrogate, or whatever...) an object without
knowing its type at runtime.

The latest of several attempts is shown below - the compiler complains about
the void* in the PrintObject function, though I thought I'd read that void*
could be used to mean "pointer to something, but I don't know what".

Can this code be modifed to get the effect I want? I'd like to avoid using
pointers to functions if possible.

Thanks!
#include <iostream.h>

// Class declarations
// ------------------

class Square{
public:
void Print();
};

void Square::Print() {
cout << "This is a square";
}

class Circle{
public:
void Print();
};

void Circle::Print() {
cout << "This is a circle";
}

// Print object function
// ---------------------

void PrintObject(voi d* object){
object->Print();
}

// Main Program
// ------------

int main(){
Square* square;
Circle* circle;

square = new Square;
circle = new Circle;

// Call member functions directly

circle->Print();
square->Print();

// Call member functions through PrintObject function

PrintObject(cir cle);
PrintObject(squ are);

return 0;

}

Jul 22 '05
12 2080
On Thu, 8 Apr 2004 19:51:23 +0100 in comp.lang.c++, "Anthony Jones"
<me@privacy.net > wrote,
I want to write a C++ equivalent, using classes and member functions so that
I can print (or draw, or interrogate, or whatever...) an object without
knowing its type at runtime.


This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[20.4] I have a heterogeneous list of objects, and my code needs to do
class-specific things to the objects. Seems like this ought to use
dynamic binding but can't figure it out. What should I do?" It is
always good to check the FAQ before posting. You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/

Jul 22 '05 #11
Anthony,

See the few additions/modifications in your code below. You are very close
but only missing a few items. You need to use virtual member functions
rather than simple member functions. Which means you need to derive from an
base class that declares a virtual member function.

"Anthony Jones" <me@privacy.net > wrote in message
news:3K******** ************@ni ldram.net...

Just a bit of background: I'm one of a group of FORTRAN programmers, looking to switch to C++. We are trying to write a few simple examples to
demonstrate the power of the language to our manager, so he will send us all on a conversion course.

One of many reasons is that our code is littered with examples of:

SUBROUTINE PRINT_ITEM(ITEM , ITEM_TYPE)
IF (ITEM_TYPE .EQ. SQUARE) THEN
CALL PRINT_SQUARE(IT EM)
ELSEIF (ITEM_TYPE .EQ. CIRCLE) THEN
CALL PRINT_CIRCLE(IT EM)
ELSEIF ...
(lots more item types)
ENDIF
END

(with apologies for sullying the group with FORTRAN code).

Obviously We need to find and modify all these blocks whenever we add a new object type, or operation.

I want to write a C++ equivalent, using classes and member functions so that I can print (or draw, or interrogate, or whatever...) an object without
knowing its type at runtime.

The latest of several attempts is shown below - the compiler complains about the void* in the PrintObject function, though I thought I'd read that void* could be used to mean "pointer to something, but I don't know what".

Can this code be modifed to get the effect I want? I'd like to avoid using
pointers to functions if possible.

Thanks!
#include <iostream.h>

// Class declarations
// ------------------
class Geometry
{
public:
virtual ~Geometry(){} // need a virtual destructor in this case

virtual void Print(){}
};

class Square{
replace with:

class Square : public Geometry{

public:
void Print();
};

void Square::Print() {
cout << "This is a square";
}

class Circle{
replace with:

class Circle : public Geometry{
public:
void Print();
};

void Circle::Print() {
cout << "This is a circle";
}

// Print object function
// ---------------------

void PrintObject(voi d* object){
object->Print();
}
replace with:

void PrintObject( Geometry* aObjectPtr )
{
aObjectPtr->Print();
}

or better yet:

void PrintObject( Geometry& aObject ) // by reference
{
aObject.Print() ;
}

// Main Program
// ------------

int main(){
Square* square;
Circle* circle;

square = new Square;
circle = new Circle;

// Call member functions directly

circle->Print();
square->Print();

// Call member functions through PrintObject function

PrintObject(cir cle);
PrintObject(squ are);
to use the reference version replace with:

PrintObject( *circle ); // dereference the pointers to get references
PrintObject( *square );

return 0;

}


Better yet is to forego dealing with pointers altogether.

int main()
{
Square lSquare;
Circle lCircle;

lCircle.Print() ;
lSquare.Print() ;

PrintObject( lSquare );
PrintObject( lCircle );

return 0;
}

Additionally, since typically a Print function would not modify the state of
it's object, it's best to declare the member function as 'const'. As in:

class Geometry
{
public:
virtual ~Geometry(){}
virtual void Print()const{}
};

And finally to show the real power:

#include <vector>

int main()
{
typedef std::vector<Geo metry*> ;

tGeoPtrs lGeoPtrs;

lGeoPtrs.push_b ack( new Circle );
lGeoPtrs.push_b ack( new Square );
lGeoPtrs.push_b ack( new Circle );
lGeoPtrs.push_b ack( new Square );
lGeoPtrs.push_b ack( new Circle );

for( tGeoPtrs::itera tor lItr = lGeoPtrs.begin( ) ; lItr != lGeoPtrs.end()
; ++lItr )
{
(*lItr)->Print();

// or

PrintObject( *lItr ); // Pointer overload

// or

PrintObject( **lItr ); // reference overload

delete *lItr; // delete it when we're done

*lItr = NULL;
}

return 0;
}

This is just the beginning of the power/expressivenes advantages of C++
versus Fortran.

Jeff F


Jul 22 '05 #12
Anthony,

See the few additions/modifications in your code below. You are very close
but only missing a few items. You need to use virtual member functions
rather than simple member functions. Which means you need to derive from an
base class that declares a virtual member function.

"Anthony Jones" <me@privacy.net > wrote in message
news:3K******** ************@ni ldram.net...

Just a bit of background: I'm one of a group of FORTRAN programmers, looking to switch to C++. We are trying to write a few simple examples to
demonstrate the power of the language to our manager, so he will send us all on a conversion course.

One of many reasons is that our code is littered with examples of:

SUBROUTINE PRINT_ITEM(ITEM , ITEM_TYPE)
IF (ITEM_TYPE .EQ. SQUARE) THEN
CALL PRINT_SQUARE(IT EM)
ELSEIF (ITEM_TYPE .EQ. CIRCLE) THEN
CALL PRINT_CIRCLE(IT EM)
ELSEIF ...
(lots more item types)
ENDIF
END

(with apologies for sullying the group with FORTRAN code).

Obviously We need to find and modify all these blocks whenever we add a new object type, or operation.

I want to write a C++ equivalent, using classes and member functions so that I can print (or draw, or interrogate, or whatever...) an object without
knowing its type at runtime.

The latest of several attempts is shown below - the compiler complains about the void* in the PrintObject function, though I thought I'd read that void* could be used to mean "pointer to something, but I don't know what".

Can this code be modifed to get the effect I want? I'd like to avoid using
pointers to functions if possible.

Thanks!
#include <iostream.h>

// Class declarations
// ------------------
class Geometry
{
public:
virtual ~Geometry(){} // need a virtual destructor in this case

virtual void Print(){}
};

class Square{
replace with:

class Square : public Geometry{

public:
void Print();
};

void Square::Print() {
cout << "This is a square";
}

class Circle{
replace with:

class Circle : public Geometry{
public:
void Print();
};

void Circle::Print() {
cout << "This is a circle";
}

// Print object function
// ---------------------

void PrintObject(voi d* object){
object->Print();
}
replace with:

void PrintObject( Geometry* aObjectPtr )
{
aObjectPtr->Print();
}

or better yet:

void PrintObject( Geometry& aObject ) // by reference
{
aObject.Print() ;
}

// Main Program
// ------------

int main(){
Square* square;
Circle* circle;

square = new Square;
circle = new Circle;

// Call member functions directly

circle->Print();
square->Print();

// Call member functions through PrintObject function

PrintObject(cir cle);
PrintObject(squ are);
to use the reference version replace with:

PrintObject( *circle ); // dereference the pointers to get references
PrintObject( *square );

return 0;

}


Better yet is to forego dealing with pointers altogether.

int main()
{
Square lSquare;
Circle lCircle;

lCircle.Print() ;
lSquare.Print() ;

PrintObject( lSquare );
PrintObject( lCircle );

return 0;
}

Additionally, since typically a Print function would not modify the state of
it's object, it's best to declare the member function as 'const'. As in:

class Geometry
{
public:
virtual ~Geometry(){}
virtual void Print()const{}
};

And finally to show the real power:

#include <vector>

int main()
{
typedef std::vector<Geo metry*> ;

tGeoPtrs lGeoPtrs;

lGeoPtrs.push_b ack( new Circle );
lGeoPtrs.push_b ack( new Square );
lGeoPtrs.push_b ack( new Circle );
lGeoPtrs.push_b ack( new Square );
lGeoPtrs.push_b ack( new Circle );

for( tGeoPtrs::itera tor lItr = lGeoPtrs.begin( ) ; lItr != lGeoPtrs.end()
; ++lItr )
{
(*lItr)->Print();

// or

PrintObject( *lItr ); // Pointer overload

// or

PrintObject( **lItr ); // reference overload

delete *lItr; // delete it when we're done

*lItr = NULL;
}

return 0;
}

This is just the beginning of the power/expressivenes advantages of C++
versus Fortran.

Jeff F


Jul 22 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2091
by: Nick Coghlan | last post by:
Thought some folks here might find this one interesting. No great revelations, just a fairly sensible piece on writing readable code :) The whole article: http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=1 The section specifically on white space: http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=3 Cheers,
12
1048
by: Anthony Jones | last post by:
Just a bit of background: I'm one of a group of FORTRAN programmers, looking to switch to C++. We are trying to write a few simple examples to demonstrate the power of the language to our manager, so he will send us all on a conversion course. One of many reasons is that our code is littered with examples of: SUBROUTINE PRINT_ITEM(ITEM, ITEM_TYPE) IF (ITEM_TYPE .EQ. SQUARE) THEN CALL PRINT_SQUARE(ITEM)
5
2118
by: Jeff Greenberg | last post by:
Not an experienced c++ programmer here and I've gotten myself a bit stuck. I'm trying to implement a class lib and I've run into a sticky problem that I can't solve. I'd appreciate any help that I can get! Consider 3 classes in the following heirarchy: base / \ deriv1 deriv2 \
5
2333
by: Adrian | last post by:
I am trying to pass the address of a C++ function into a Fortran routine to enable the Fortran routine to call this C++ function. I have to do it this way as our build process does not allow circular dependencies of DLL's. Does anyone know how to do this, I have tried everything in my book. I have a C++ function GetP: DllExport void GetP()
3
11461
by: David Dvali | last post by:
Hello. I have one small program which I need to convert in C#. The original source codes are written in Fortran 77. Can anybody advice me what is the easy way to do this task? Or may be there is some tools for it? Thank you.
2
7248
by: | last post by:
Help! I'm new to c++, and am breaking my teeth on MS Visual C++ (bundled within Visual Studio .NET 2003). Am trying to link simple c++ code to fortran dlls created in Compaq Visual Fortran (v6.1). Posts concerning this topic are common, but none of the posted solutions I've tried work correctly with the above software. The linker can't seem to find the dll (reports 'unresolved external symbol __imp__IMSL_FUN@8'; IMSL_FUN.dll is the f77...
8
2084
by: Daz | last post by:
Hi all! This question may hopefully spark a little debate, but my problem is this: I am sure it's not just me who struggles to think up names for variables. Obviously, thinking up a name 'can' be simple, but when you are trying to create variable names that are easy to remember, descriptive, and not more than say 15-20 characters long, I come a cropper! Would anyone be able to give me any pointers as to how I can
12
2421
by: StephQ | last post by:
I face the following problem. I wrote a poor's man plotting function: computePlot. This function append some x-values belonging to step and the correseponding f( x ) (for a given const member function f that takes and return a double) values to a reference stringstream, let's call this ss. Then I usually use ss.str() to transfer the results in a file and plot these results using an external software like gnuplot.
7
3819
by: ghulands | last post by:
I am having trouble implementing some function pointer stuff in c++ An object can register itself for many events void addEventListener(CFObject *target, CFEventHandler callback, uint8_t event); so I declared a function pointer like typedef void (CFObject::*CFEventHandler)(CFEvent *theEvent);
0
8686
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8615
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9173
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8882
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6533
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3057
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2345
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2009
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.