473,566 Members | 3,307 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Which is the better way to define methods?

My c++ text tells me that I should define methods this way:

class Stack
{
int method(double t);
Stack(int s);
...
}

int Stack::method(d ouble t)
{
/* behavior */
}

but my experience with Java tells me that this way is better:

class Stack
{
int method(double t)
{
/* behavior */
}

Stack(int s)
{
/* behavior */
}
}

Which way do you use? Should I use the first or the second? I'd
rather develop good habits as I teach myself C++ rather than have to
go back and fix bad ones later. Thank you in advance for the help.
Jul 22 '05 #1
14 1640
On 7 Jul 2004 13:24:25 -0700, Blue Ocean <bl*********@ho tmail.com> wrote:
My c++ text tells me that I should define methods this way:

class Stack
{
int method(double t);
Stack(int s);
...
}

int Stack::method(d ouble t)
{
/* behavior */
}

but my experience with Java tells me that this way is better:

class Stack
{
int method(double t)
{
/* behavior */
}

Stack(int s)
{
/* behavior */
}
}

Which way do you use? Should I use the first or the second? I'd
rather develop good habits as I teach myself C++ rather than have to
go back and fix bad ones later. Thank you in advance for the help.


If you use the second method then you are putting all you code into header
files. Some people don't like that, either because they think the code
should be private, or they worry about the extra compilation time from
large header files.

But really it's not a big issue. With more and more people writing
template code (where you have to put the code in the header file anyway)
your method is becoming much more common.

john
Jul 22 '05 #2
Something that calls itself Blue Ocean wrote:
My C++ text tells me that
Which C++ text are you reading?
I should define methods this way:

class Stack { public: int method(double t);
Stack(int s);
...
};
inline int Stack::method(d ouble t) {
/* behavior */
}

but my experience with Java tells me that this way is better:

class Stack { public: int method(double t) {
/* behavior */
}

Stack(int s) {
/* behavior */
}
};

Which way do you use? Should I use the first or the second?
I'd rather develop good habits as I teach myself C++
rather than have to go back and fix bad ones later.


You need to *unlearn* your Java habits.
If you define constructors, functions or operators
within the class definition, they are inline functions.
You can move the function definition out of the class definition
but you must qualify it with the 'inline' keyword
or move the definition into a separate *implementation * source file
where it will be compiled exactly *once*!
Jul 22 '05 #3
It's purely cosmetic.

I myself would prefer:

// Poo.hpp (HEADER FILE)

class Poo
{
private:

double data;

public:

void Increase5Percen t();
void Increase20Perce nt();
};

inline void Poo::Increase5P ercent()
{
double *= 1.05;
}

inline void Poo::Increase20 Percent();
{
double *= 1.2;
}
OVER:

// Poo.hpp (HEADER FILE)

class Poo
{
private:

double data;

public:

void Poo::Increase5P ercent()
{
double *= 1.05;
}

void Poo::Increase20 Percent()
{
double *= 1.2;
}
};
Consider if you had 23 inline functions, it's nice to still have a nice
compact class declaration.
-JKop
Jul 22 '05 #4
JKop posted:

class Poo
{
private:

double data;

public:

void Poo::Increase5P ercent()

That would be the woes of copy and paste.

{
double *= 1.05;
}

void Poo::Increase20 Percent()

and again

{
double *= 1.2;
}
};

-JKop
Jul 22 '05 #5
Blue Ocean wrote:
My c++ text tells me that I should define methods this way:

class Stack
{
int method(double t);
Stack(int s);
...
}

int Stack::method(d ouble t)
{
/* behavior */
}

but my experience with Java tells me that this way is better:

class Stack
{
int method(double t)
{
/* behavior */
}

Stack(int s)
{
/* behavior */
}
}

Which way do you use? Should I use the first or the second? I'd
rather develop good habits as I teach myself C++ rather than have to
go back and fix bad ones later. Thank you in advance for the help.

The first, with separate files for the class definition and
implementation. If I decide that I want to change how
Stack::method(d ouble) works, I don't have to recompile everybody who
*uses* Stack, just Stack itself and then relink.
Jul 22 '05 #6
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote in message news:<cc******* ***@nntp1.jpl.n asa.gov>...
Something that calls itself Blue Ocean wrote:
My C++ text tells me that


Which C++ text are you reading?


_The C++ Programming Language_ by Bjarne Stroustrup.
[snip]


You need to *unlearn* your Java habits.
If you define constructors, functions or operators
within the class definition, they are inline functions.
You can move the function definition out of the class definition
but you must qualify it with the 'inline' keyword
or move the definition into a separate *implementation * source file
where it will be compiled exactly *once*!


So . . . I wasn't thinking at all about inline functions. If a method
is defined inside the class definition, that's what happens? So, tell
me if this is right (for normal, non-inlined methods:

=============== =============== ==========
/* file.h */
class Stack
{
private:
int somethingoranot her;

public:
Stack();
~Stack();
int foo(double bar);
}

/* file.cpp */
int Stack::foo(doub le bar)
{
//Behavior
}

Stack::Stack()
{
//Behavior
}
=============== =============== ==========

If that is right, let me extend the question a little. Should I
declare private methods in the .h file? Or should I declare them in
the .c file?
Jul 22 '05 #7
Blue Ocean wrote:
E. Robert Tisdale wrote:
[snip]

You need to *unlearn* your Java habits.
If you define constructors, functions or operators
within the class definition, they are inline functions.
You can move the function definition out of the class definition
but you must qualify it with the 'inline' keyword
or move the definition into a separate *implementation * source file
where it will be compiled exactly *once*!


So . . . I wasn't thinking at all about inline functions.
If a method is defined inside the class definition, that's what happens?
So, tell me if this is right (for normal, non-inlined methods:
=============== =============== ==========

#ifndef guard_file_h
#define guard_file_h // file.h

class Stack {
private:
int somethingoranot her;

public:
Stack(void);
~Stack(void);
int foo(double bar);
};
#endif// guard_file_h
// file.cpp #include "file.h"
int Stack::foo(doub le bar) {
// Behavior
}

Stack::Stack(vo id) {
// Behavior
}
=============== =============== ==========

If that is right, let me extend the question a little.
Should I declare private methods in the .h file?
Or should I declare them in the .c file?


You must *declare* them in the class definition.
You may *define* them in the header file as *inline* functions.
Jul 22 '05 #8
"Blue Ocean" <ag***********@ gmail.com> wrote in message
news:af******** *************** ***@posting.goo gle.com...
If that is right, let me extend the question a little. Should I
declare private methods in the .h file? Or should I declare them in
the .c file?


In Java, you'll often find private methods, and especially static private
methods, which in C++ are best implemented as non-member utility functions
within the .cpp file.

C and C++ are abit archaic in that they use this subdivision between a
header and a source file, which is an artefact from the way the compilers
work. Java avoids this problem because the equivalent of a header is
generated by the compiler automatically, in a binary form.
The only benefit of headers is that they give you more control regarding
what will be seen by a user of a library. But it is also a burden...

A rule of thumb in C/C++ is that you keep as little information as possible
outside of the headers.
You therefore try to only put in a .h file what has to be accessible to the
users -- the exception being private members of a class, which are not used
from the outside, but need to be declared within a class definition ( class
A { /*here*/ }; ).
Sometimes, putting less information in a header requires specific
workarounds, such as the "pimpl" idiom or the use of abstract base classes.

hth,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- e-mail contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 22 '05 #9
Blue Ocean wrote:
My c++ text tells me that I should define methods this way:

class Stack
{
int method(double t);
Stack(int s);
...
} I prefer:
struct Stack
{
int method(double t);
Stack(int i);
};

or

class Stack
{
public:
// Constructors:
Stack(int s);

// Methods in alphabetical order
int method(double t) const;
};


int Stack::method(d ouble t)
{
/* behavior */
}

but my experience with Java tells me that this way is better:
My experience with C++ tells me that a class's default
access is private and a struct is public.


class Stack
{
int method(double t)
{
/* behavior */
}

Stack(int s)
{
/* behavior */
}
}

Which way do you use? Should I use the first or the second? I'd
rather develop good habits as I teach myself C++ rather than have to
go back and fix bad ones later. Thank you in advance for the help.


I prefer to list all the declarations of members and methods in
the class and their implementations outside of the class.

For simple functions, I declare them as inline in the header file
(the file containing the class declaration). For more complex
methods, I place them into a source / .cpp / translation unit.

With bigger projects, changing the content of a method residing
in a separate translation unit reduces the need to recompile all
other files that depend on the header file. Templates are another
situation though. :-(
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 22 '05 #10

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

Similar topics

14
2125
by: Dan | last post by:
I have seen differing ways to pass values to a class: $db=new mysqlclass('localhost','user','passwd','database'); ..... OR $db=new mysqlclass() $db->host='localhost'; $db->user='user'; $db->passwd='passwd';
17
2531
by: lawrence | last post by:
How is it possible that the question "How do I detect which browser the user has" is missing from this FAQ: http://www.faqts.com/knowledge_base/index.phtml/fid/125 and is only here on this with a link to old information that suggests use of "navigator": http://developer.irt.org/script/43.htm
52
2248
by: Darklight | last post by:
Question: Write a function named sumarrays() that accepts two arrays that are the same size. The function should add each element in the array together and place the values in the thrid array. Which answer is the better practice; /*EX9.C*/ #include<stdio.h> #define MAX 5
18
2038
by: Sean Kirkpatrick | last post by:
I have a very ugly problem and I need some sincere guidance. My legacy VB6 application depends heavily on DAO, especially as it relates to custom properties on database objects. These custom properties are, as I understand it, not avabilable with SQL Server, which we need to migrate to in the not too distant future. My boss, the owner of...
2
2430
by: steve | last post by:
Hi, I'm trying to use a protocol class as a template parameter. The protocol class defines its own types and methods for working with them. The template class uses the types defined by the protocol and various methods, however I get errors when trying to compile this in Xcode while in Codewarrior it works fine. I'm looking for a way to...
14
9828
by: Derek Basch | last post by:
This one has always bugged me. Is it better to just slap a "self" in front of any variable that will be used by more than one class method or should I pass around variable between the methods? Flamewar........NOW! jk, I really do want other opinions. Thanks, Derek
20
1530
by: Parag | last post by:
Hi, I am trying to figure out best testing tool for my project. I have narrowed down my requirements to two tools NUNIT and VSTS unit. But I have used neither and I have to use only one of them. Hence can someone who has used them before share his/her experience on them so that I can get a better idea and make a proper choice ? Any link or...
2
2118
by: Bill Jackson | last post by:
For example, class A: def __init__(self,a): self.a = a def __eq__(self, other): return self.a == other.a class B: def __init__(self,b):
8
2347
by: =?Utf-8?B?eWRibg==?= | last post by:
I need to write a program validate a text file in CSV format. So I will have a class DataType and a lot of of derived class for various type, e.g. IntType, StringType, FloatType, MoneyType, ... etc. For each column of a type, it may accept null/empty value. or not. It may have various max length for StringType, IntType,... etc.
0
7673
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...
0
7584
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...
0
8109
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
5485
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...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3643
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...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2085
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
0
926
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...

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.