473,699 Members | 2,364 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 #1
12 1048

"Anthony Jones" <me@privacy.net > wrote in message
news:3K******** ************@ni ldram.net...
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.
You mean without knowing its type "at compile time"? It has to be known at
run-time, or you'd never be able to do *anything* with it! :-)

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".

Yes, you can use a void* to store any other pointer, but you can never *use*
that pointer for anything (dereference it) unless you first cast it back to
whatever it's supposed to be.

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

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


What you want to do instead of using a void* is to have a base class from
which all your specific shapes inherit. Then you make a virtual Print
function in the base class, and have each derived class overried that
function to do its own version of printing.

You really need to do some reading up on base classes, inheritance, and
virtual functions before attempting to go further on this.

-Howard


Jul 22 '05 #2

"Anthony Jones" <me@privacy.net > wrote in message
news:3K******** ************@ni ldram.net...
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.
You mean without knowing its type "at compile time"? It has to be known at
run-time, or you'd never be able to do *anything* with it! :-)

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".

Yes, you can use a void* to store any other pointer, but you can never *use*
that pointer for anything (dereference it) unless you first cast it back to
whatever it's supposed to be.

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

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


What you want to do instead of using a void* is to have a base class from
which all your specific shapes inherit. Then you make a virtual Print
function in the base class, and have each derived class overried that
function to do its own version of printing.

You really need to do some reading up on base classes, inheritance, and
virtual functions before attempting to go further on this.

-Howard


Jul 22 '05 #3
What you want to do instead of using a void* is to have a base class from
which all your specific shapes inherit. Then you make a virtual Print
function in the base class, and have each derived class overried that
function to do its own version of printing.

You really need to do some reading up on base classes, inheritance, and
virtual functions before attempting to go further on this.


I also suggest that you have a look at some examples
available on the internet.
google for "c++ polymorphism example" ... you might find
some examples with circles and rectangles...

See for example http://onestepback.org/articles/poly/
Jul 22 '05 #4
What you want to do instead of using a void* is to have a base class from
which all your specific shapes inherit. Then you make a virtual Print
function in the base class, and have each derived class overried that
function to do its own version of printing.

You really need to do some reading up on base classes, inheritance, and
virtual functions before attempting to go further on this.


I also suggest that you have a look at some examples
available on the internet.
google for "c++ polymorphism example" ... you might find
some examples with circles and rectangles...

See for example http://onestepback.org/articles/poly/
Jul 22 '05 #5

"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.


For God's sake! VIRTUAL FUNCTIONS

Look it up in your favourite text book. They do exactly what you need.

john
Jul 22 '05 #6

"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.


For God's sake! VIRTUAL FUNCTIONS

Look it up in your favourite text book. They do exactly what you need.

john
Jul 22 '05 #7
Anthony Jones wrote:
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
Yikes.

(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".
Yes, and it also means "no type safety". void* should be avoided, and is
certainly not the right way to accomplish polymorphic behavior (which is
what you are looking for, whether you know that or not).

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>
I realize you are new to this, so please understand that I'll point out
any and all errors I spot in your code, regardless of whether they are
relevant to the immediate question. Also, my definition of an 'error'
includes anything that is not defined by the C++ standard, anything that
may behave unexpectedly, or that may behave differently on different
implementations (even if one of the "different implementations " is a
hypothetical implementation that does not actually exist). This is
standard practice for many of the people in this group.

That said, <iostream.h> is not part of the C++ standard. It is old,
pre-standard C++. Standard C++ uses <iostream> (with no .h).

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

class Square{
public:
void Print();
};
In order to achieve polymorphic behavior, you need a few things that you
are missing: Inheritance, and virtual functions. Your example involves
shapes. Great, so create a class representing a shape. It will serve as
the base class for you other shapes.

class Shape
{
public:
virtual void Print() = 0;
};

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

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

The "class Square : public Shape" part can be read as "Square IS A
Shape". This is often referred to as the 'is-a' relationship. Squares
and Circles are both types of Shapes, and thus share some of the same
functionality -- in particular, they all have the ability to perform the
'Print' operation.

The 'virtual' qualifier on Shape::Print() just means "this function can
behave differently in different base classes". This allows Square and
Circle to give their own version of Print() that does what they need it
to do. The '= 0' part is a bit more confusing. It has basically 2
effects: 1) It allows Shape to decline to implement Print(). There's no
reasonable way to print a generic shape, so this makes sense. It
essentially requires base classes to provide Print() instead (though a
base class can pull the same trick, passing the burden of implementing
the function onto /its/ base classes). 2) It makes Shape an abstract
class, which is a class that can really only be used as a base class.
You can't create an object of type Shape, because Shape is not a
complete class.

void Square::Print() {
cout << "This is a square";
In modern C++, 'cout' (along with most standard library names) resides
in namespace std. This means that the fully qualified name is std::cout.
You can use this fully-qualified name, or you can put a line like this:

using namespace std;

at the top of your source files, just after the #include directives.
This is sort of the lazy way of doing it, and can be bad in some cases,
but it's the easiest way to get started. There are other options as
well, but you'll learn about that later.

Other than that, no changes are required here.
}

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

void Circle::Print() {
cout << "This is a circle";
Same comments as for Square::Print() .
}

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

void PrintObject(voi d* object){
Now, you don't want to use void* here. What you want is a function to
print an object. More specifically, a Shape. So try this instead:

void PrintShape(Shap e *shape)
{
object->Print();
shape->Print();
}

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

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

square = new Square;
circle = new Circle;
Generally, you shouldn't use 'new' unless you absolutely have to. It
tends to be used in real programs that do what you are demonstrating, so
its use here isn't completely inappropriate, but normally when you want
a Square you should just say

Square my_square;

It's also worth noting that a more typical way of doing what you are
doing would be like this:

Shape *square;
Shape *circle;

square = new Square;
circle = new Circle;

In fact, you'd probably be most likely to have a collection of Shape
pointers (in an array, or a container class). Such collections generally
have to be homogeneous, so they can't contain Square pointers and Circle
pointers. Luckily they don't need to, because Shape pointers can point
to Squares, Circles, and any other type that IS A Shape.

// Call member functions directly

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

// Call member functions through PrintObject function

PrintObject(cir cle);
PrintObject(squ are);
Replace these with the new name 'PrintShape' and you're all set.

return 0;

}


-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #8
Anthony Jones wrote:
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
Yikes.

(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".
Yes, and it also means "no type safety". void* should be avoided, and is
certainly not the right way to accomplish polymorphic behavior (which is
what you are looking for, whether you know that or not).

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>
I realize you are new to this, so please understand that I'll point out
any and all errors I spot in your code, regardless of whether they are
relevant to the immediate question. Also, my definition of an 'error'
includes anything that is not defined by the C++ standard, anything that
may behave unexpectedly, or that may behave differently on different
implementations (even if one of the "different implementations " is a
hypothetical implementation that does not actually exist). This is
standard practice for many of the people in this group.

That said, <iostream.h> is not part of the C++ standard. It is old,
pre-standard C++. Standard C++ uses <iostream> (with no .h).

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

class Square{
public:
void Print();
};
In order to achieve polymorphic behavior, you need a few things that you
are missing: Inheritance, and virtual functions. Your example involves
shapes. Great, so create a class representing a shape. It will serve as
the base class for you other shapes.

class Shape
{
public:
virtual void Print() = 0;
};

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

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

The "class Square : public Shape" part can be read as "Square IS A
Shape". This is often referred to as the 'is-a' relationship. Squares
and Circles are both types of Shapes, and thus share some of the same
functionality -- in particular, they all have the ability to perform the
'Print' operation.

The 'virtual' qualifier on Shape::Print() just means "this function can
behave differently in different base classes". This allows Square and
Circle to give their own version of Print() that does what they need it
to do. The '= 0' part is a bit more confusing. It has basically 2
effects: 1) It allows Shape to decline to implement Print(). There's no
reasonable way to print a generic shape, so this makes sense. It
essentially requires base classes to provide Print() instead (though a
base class can pull the same trick, passing the burden of implementing
the function onto /its/ base classes). 2) It makes Shape an abstract
class, which is a class that can really only be used as a base class.
You can't create an object of type Shape, because Shape is not a
complete class.

void Square::Print() {
cout << "This is a square";
In modern C++, 'cout' (along with most standard library names) resides
in namespace std. This means that the fully qualified name is std::cout.
You can use this fully-qualified name, or you can put a line like this:

using namespace std;

at the top of your source files, just after the #include directives.
This is sort of the lazy way of doing it, and can be bad in some cases,
but it's the easiest way to get started. There are other options as
well, but you'll learn about that later.

Other than that, no changes are required here.
}

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

void Circle::Print() {
cout << "This is a circle";
Same comments as for Square::Print() .
}

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

void PrintObject(voi d* object){
Now, you don't want to use void* here. What you want is a function to
print an object. More specifically, a Shape. So try this instead:

void PrintShape(Shap e *shape)
{
object->Print();
shape->Print();
}

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

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

square = new Square;
circle = new Circle;
Generally, you shouldn't use 'new' unless you absolutely have to. It
tends to be used in real programs that do what you are demonstrating, so
its use here isn't completely inappropriate, but normally when you want
a Square you should just say

Square my_square;

It's also worth noting that a more typical way of doing what you are
doing would be like this:

Shape *square;
Shape *circle;

square = new Square;
circle = new Circle;

In fact, you'd probably be most likely to have a collection of Shape
pointers (in an array, or a container class). Such collections generally
have to be homogeneous, so they can't contain Square pointers and Circle
pointers. Luckily they don't need to, because Shape pointers can point
to Squares, Circles, and any other type that IS A Shape.

// Call member functions directly

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

// Call member functions through PrintObject function

PrintObject(cir cle);
PrintObject(squ are);
Replace these with the new name 'PrintShape' and you're all set.

return 0;

}


-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #9
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 #10

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
2081
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 \
81
7305
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
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
9174
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
8884
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...
0
7751
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6534
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
4376
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4629
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
2347
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.