What are the data types use in c plus plus?
Binary data is intrinsically numeric, therefore every type (including user-defined types) can be represented as a number. Even an executable or a file is nothing more than an extremely large number, in binary, made up of a specific sequence of bits grouped in various ways (bytes, words, dwords, etc), each of which is a number in its own right.
What these numbers actually represent is purely a matter of interpretation. While a char type is typically used to represent an alphanumeric character or symbol, it is really just a character code (a number in the range 0 to 255) that can be mapped to a symbolic character in the ASCII character set. A char is therefore no different to a byte and can represent an actual number just as easily as it can a character.
The primitive types are: unsigned short int, short int, unsigned long int, long int, int, unsigned int, char, wchar_t, bool, float, double and long double, each of which is intrinsically numeric. All user-defined types, including classes and structures, are derived from some combination of these primitive types.
What is a macro in c plus plus?
A macro is preprocessor definition that is processed prior to compilation. All occurances of a macro within your C++ source code are replaced with the macro definition, much like an automated search-and-replace-all operation. If the macro's definition is a function with one or more arguments, then the function is inline expanded within your code, replacing the defined arguments with the arguments that were passed to the macro. However, macro functions are not type safe and cannot be debugged because they only exist in your source code; the compiler only sees the intermediate code emitted by the preprocessor, at which point all macro definitions will no longer exist. To address this problem, C++ also supports the concept of template functions, which not only eliminates any unwanted inline expansion (resulting in smaller code), but also ensures that all calls to the function are type safe and can be debugged in the normal way. That said, macro functions, when used appropriately, can greatly simplify your code and can achieve things that would be difficult if not impossible to achieve with C++ alone. The ability to use code fragments via a macro is one such possibility. However, when combined with preprocessor directives such as #ifdef DEBUG, macros can also be used to provide useful and powerful debugging routines that only exist in debug code, compiling to no code in release builds. This cannot be achieved with C++ alone.
Disadvantages of friend function in c plus plus?
C is not object oriented programming language thus there are no friend functions in C.
In C++, which is object oriented, the advantage of a friend is that it allows code that cannot otherwise be regarded as being a member of the class to gain private access to the class representation, where public access to the representation would be considered undesirable. Although many see friendship as an undermining of encapsulation, the reality is it strengthens encapsulation by limiting exposure to the representation to only those functions that actually require that access. Public access is fully accessible, of course, but is not always desirable. Interfaces must be kept as simple as possible, but exposing an interface that is only of use to a few non-member functions is less desirable than simply making those functions friends of the class.
It is important to understand the relationships between functions and classes. All functions can be divided into one of three distinct categories with respect to any one class: non-member functions; static member functions or; nonstatic member functions.
Nonstatic member functions of a class have all three of the following properties:
1. The function has private access to the class representation.
2. The function is scoped to the class.
3. The function must be invoked upon an object of the class (has a 'this' pointer).
Static member functions only have the first two properties while friend functions only have the first property. External (non-friend) functions do not have any of these properties.
The only disadvantage to a friend function is when that friend is outwith the control of the class designer. Since friends have private access they must obey the class invariants, just as any member of the class must. Although they are not members of the class per se, they must be implemented just as if they were. In other words, they must not invalidate the representation. When the class designer has full control over the friends of that class then this is not a major problem. But when third-party programmers have access to the friend implementations, encapsulation can no longer be guaranteed by the class designer -- it is seriously undermined. But when used appropriately, friends actively re-enforce encapsulation and are no more an undermining of encapsulation than is public inheritance.
What is file mode in c plus plus?
There are 6 main types of file opening mode:
* "r". Open file for reading and file must exist; * "w" Open file for writing. If file does not exist it is created or if life already exist it's content is erased. * "a" Open file for appending. It adds all information at the end of the file leaving old data untouched. If file does not exist it is created. * "r+" Open file for reading and writing and file must exist. * "w+" Open file for writing and reading. If file does not exist it is created or if life already exist it's content is erased. * "a+" Open file for appending and reading. Again all new data is written at the end of the file old data leaving untouched. If file does not exist it is created. (You can read old data by moving pointer in file using fseek or rewind functions from stdio.h. But all writing operations will be done at the end of the file no matter how you change pointer) It is assumed by default that file will be standard ASCII text file in order to open file as binary file, you need to add "b" indicator:
FILE *myFile = fopen("myfile.txt", "wb");
/ * following two has identical meaning */
FILE *myFile = fopen("myfile.txt", "w+b");
FILE *myFile = fopen("myfile.txt", "wb+");
What is the major difference between c and c plus plus?
C is an imperative (procedural), structured paradigm language whereas C++ is multi-paradigm: procedural, functional, object-oriented and generic. Both are high-level, abstract languages. While C's design provides constructs that map efficiently to machine code instructions, C++ is more abstract, relying heavily upon object-oriented principals. However, both are equally capable of producing highly-efficient machine code programs. C++ derives almost directly from C thus everything you can do in C you can do in C++ with relatively minor alterations to the source. C++ was originally called C with Classes and that pretty much sums up the main difference between the two languages. However, there are many subtle differences.
One key difference between C and C++ is in the struct data type. In C, a struct can only contain public data members (with no methods). In C++, a struct is similar to a class, combining data and the methods that operate upon that data into a single entity (an object). The only difference between a C++ struct and a C++ class is that class members are private by default whereas struct members are public by default.
Another key difference is that because C++ is object oriented, there is much less reliance upon the programmer to manage memory. Each object takes care of its own memory allocations (including embedded objects), thus the programmer simply creates and destroys objects as needed. Thus C++ is much easier to work with, especially with regards to highly-complex hierarchical structures, but is every bit as efficient as C.
Both languages are highly popular and there are few architectures that do not implement suitable compilers for both. Thus they are both highly portable. However, the object oriented approach to programming gives C++ a major advantage over C in terms of code re-usability, scalability and robustness.
Why do you use standard template library in C plus plus?
Strictly speaking there is no need for function templates -- you could do it all by hand if you really wanted to. However, anything that aids in the reduction of duplicate source code is "a good thing" in my book. Code duplication increases code maintenance overheads, there's always the chance you'll forget to propagate changes consistently, and writing variations of a function that may or may not be used is simply a waste of time and effort.
To understand the need for function templates it's best to look at how they actually work. Let's consider the following two function declarations:
int GetMax(int a, int b){return(a>b?a:b);};
float GetMax(float a, float b){return(a>b?a:b);};
We can see that both functions have exactly the same body:
{return(a>b?a:b);};
These examples are fairly simple, but whether the function is complex or not, every time we need to pass a new data type to the GetMax() function we must declare a new definition of that function in order to handle that specific data type. Or we could write out every conceivable version of the GetMax() function in full, whether we intend to actually use it or not! That's certainly an option, but in a more complex function we may later decide to alter the implementation, in which case we must duplicate those changes across ever occurrence of the function. That's a lot of unnecessary work for just one function, and may introduce errors if we're not careful with our propagation of changes.
Thankfully, the compiler can do all this work for us. We need only define the function once, and once only, and the compiler will generate all the necessary code based upon the type of data we actually pass the function. This ensures we don't create copies of the function we will never use, and greatly reduces the maintenance overhead should we ever need to alter the implementation of the function.
We do this by using a function template.
template
T GetMax(T a, T b){return(a>b?a:b);};
Note that this is not a function, per se. It is a template for a function, whereby the variable T denotes a generic data type. Whenever we make a call to GetMax(), the compiler will automatically generate the necessary code for the actual function we need, replacing the generic data type T with the actual data type we pass into the function, such as int, or float.
int a=1, b=2;
int i=GetMax(i,j); // Generates the int variation of the function.
float x=0.3, y=1.2;
float f=GetMax(x,y); // Generates the float variation of the function.
Now that we have a function template, we are no longer restricted to ints and floats any more. We can now use GetMax() with any data type we wish, without having to write specific functions for those types. The compiler does it all for us, automatically.
DWORD p=0x000000FF, q=0x00000000;
DWORD d=GetMax(p,q); // Generates a new variation of the function.
Write down a program structure of c plus plus?
C++ programs are structured with data types and functions, much like C before it. However, unlike C, data types and functions can be combined to create entities that encapsulate a set of data and provide an interface to operate upon that data. These data types are known as classes, from which objects can be instantiated. Classes may also contain static data and methods which are local to the class rather than to a specific instance of the class. Although C++ is a general purpose, object-oriented programming language, it is also backwardly compatible with C and programs can be written using 4 different programming styles: procedural programming, data abstraction, object-oriented programming and generic programming. Most C++ programs are written using a combination of these styles.
What is explicit copy constructor?
An explicit constructor is one that is declared explicit and thus prevents implicit construction of an object. To understand explicit construction you must first understand implicit construction.
Consider the following code that uses a simple class, Square, to compute the square of any given integer:
#include
using namespace std;
class Square
{
private:
int m_number;
public:
Square(int number):m_number(number*number){}
friend void display(Square square);
};
void display(Square square)
{
cout << "Number = " << square.m_number << endl;
}
int main()
{
Square ten(10); // Explicit construction
Square twenty=20; // Implicit construction
display(ten);
display(twenty);
display(30); // What does this mean?
return(0);
}
Output:
Number = 100
Number = 400
Number = 900
Although there's nothing intrinsically wrong with the line display(30), it's not exactly clear to the reader what this line does. The display() function clearly expects an instance of a Square object, yet we're passing a literal constant.
The clue is the implicit constructor call, Square twenty = 20. Although we declared no assignment operator that accepts a literal constant, the statement implies we call the constructor, Square(int). In other words, the line is equivalent to explicitly calling Square twenty(20).
This is really no different to the way primitives work. That is, int x=5 is the same as calling int x(5), but the former is a more natural form of assignment. However, this behaviour is not always desirable. While Square twenty=5 may be fine, the unwanted side effect is that it also allows us to make ambiguous calls, like display(30).
Although the line display(30) forces the display()function to construct a local Square object using implicit construction, it's not obvious to the reader that an object is created (and subsequently destroyed), and as a result of this it isn't obvious to the reader why display(30) would produce the result Number = 900.
Note that while this usage may well be obvious to the developer while writing the code, when the developer revisits the code later, it may not be quite so obvious. And if the developer has trouble reading their own code, you can imagine how difficult it would be for a third party to understand the same code.
To avoid this problem, we must declare the constructor to be explicit:
explicit Square( int number ):m_number(number*number){}
As soon as we do this, the lines Square twenty = 20 and display(30) become invalid. To rectify this, we must replace them with calls to the explicit constructor instead:
int main()
{
Square ten(10); // Explicit constructor
Square twenty(20); // Explicit constructor
display(ten);
display(twenty);
display(Square(30)); // Explicit constructor
return(0);
}
Now it is much clearer to the reader what's going on. Although we've lost the ability to implicitly construct a Squareobject, we've assured our code remains readable at all times by enlisting the help of the compiler to ensure that we never unintentionally construct a Square object via implication.
What are the rules for inline functions in c plus plus?
When you mark function as inline compiler puts the whole body of function in those places it is called, similar idea as in macros. If you do not mark function as inlinecompiler inside still decides which functions should be inline and which not. Inline function is less performance costly especially if function is called very often. Why it is lest performance costly? Because to invoke function you need to prepare parameters, put them to stack, make jump and etc. and all those steps are eliminated if function is inline.
Example (very basic):
inline int sum(int a, int b) {
return a + b;
}
int c, d;
c = sum(2, 3); /* compiler will change to 2 + 3 */
d = sum(2, 5); /* this one will be changed to 2 + 5 */
Full inline functions are allowed in ANSI/ISO C99.
What does c plus plus certification mean?
C++ was originally called "C with Classes" in 1979, as that is precisely what C++ was at the time. The name was changed to C++ in 1983. ++ is the increment operator in C, thus C++ literally means C=C+1. Hence C++ is the next "incremental" version of C. By rights it should really be called ++C (prefix increment) because, although C++ (postfix increment) increments C, the evaluation is the original value of C.
Can a static function be made virtual?
No. Virtual functions are invoked according to the runtime type of the object. That is; the most-derived override is automatically invoked even when the runtime type of the object cannot be determined at compile time. This is achieved through the object's virtual table. Static methods do not have any object associated with them; they can be invoked even when no object of the type exists. Without an object, there can be no virtual table. Thus static functions cannot be virtual. They are mutually exclusive concepts.
It means you hold down the <Alt> key, press <C>, and then release them both. Interpretation of this action is dependent on the particular application. Look at the menu bar. If there is a word with a C that is underlined, then <Alt><C> will invoke that item. Otherwise, consult the documentation for keyboard shortcuts. For example, Mozilla Firefox defines <Alt><F><C> as the command to close a tab.
C program for the two dimensional array repesentation of priority queue?
//implement double ended queue using array.
#include<stdio.h>
#include<conio.h>
#define SIZE 20
typedef struct dq_t
{
int front,rear;
int item[SIZE];
}deque;
/********** Function Declaration begins **********/
void create(deque *);
void display(deque *);
void insert_rear(deque *, int);
void insert_front(deque *, int);
int delete_front(deque *, int);
int delete_rear(deque *, int);
/********** Function Declaration ends **********/
void main()
{
int data,ch,x;
deque DQ;
clrscr();
create(&DQ);
printf("\n\t\t Program shows working of double ended queue");
do
{
printf("\n\t\t Menu");
printf("\n\t\t 1: insert at rear end");
printf("\n\t\t 2: insert at front end");
printf("\n\t\t 3: delete from front end");
printf("\n\t\t 4: delete from rear end");
printf("\n\t\t 5: exit. ");
printf("\n\t\t Enter choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
if (DQ.rear >= SIZE)
{
printf("\n Deque is full at rear end");
continue;
}
else
{
printf("\n Enter element to be added at rear end :");
scanf("%d",&data);
insert_rear(&DQ,data);
printf("\n Elements in a deque are :");
display(&DQ);
continue;
}
case 2:
if (DQ.front <=0)
{
printf("\n Deque is full at front end");
continue;
}
else
{
printf("\n Enter element to be added at front end :");
scanf("%d",&data);
insert_front(&DQ,data);
printf("\n Elements in a deque are :");
display(&DQ);
continue;
}
case 3:
x = delete_front(&DQ,data);
if (DQ.front==0)
{
continue;
}
else
{
printf("\n Elements in a deque are :");
display(&DQ);
continue;
}
case 4:
x = delete_rear(&DQ,data);
if (DQ.rear==0)
{
continue;
}
else
{
printf("\n Elements in a deque are :");
display(&DQ);
continue;
}
case 5: printf("\n finish");
return;
}
}
while(ch!=5);
getch();
}
/********** Creating an empty double ended queue **********/
/********** Function Definition begins **********/
void create(deque *DQ)
{
DQ->front=0;
DQ->rear =0;
}
/********** Function Definition ends **********/
/********** Inserting element at rear end **********/
/********** Function Definition begins **********/
void insert_rear(deque *DQ, int data)
{
if ((DQ->front 0)
{
printf("\n Underflow");
return(0);
}
else
{
DQ->rear = DQ->rear -1;
data = DQ->item[DQ->rear];
printf("\n Element %d is deleted from rear:",data);
}
if (DQ->front==DQ->rear)
{
DQ->front =0;
DQ->rear = 0;
printf("\n Deque is empty(rear end)");
}
return data;
}
/********** Function Definition ends **********/
/********** Displaying elements of DEQUE **********/
/********** Function Definition begins **********/
void display(deque *DQ)
{
int x;
for(x=DQ->front;x<DQ->rear;x++)
{
printf("%d\t",DQ->item[x]);
}
printf("\n\n");
}
/********** Function Definition ends **********/
Where can you download a free turbo c plus plus tutorial?
You can download Turbo C++ from the Embarcadero website for free. Embarcadero now own and develop all CodeGear products previously owned and developed by Borland, including the latest version of C++ Builder.
How do write a program in c plus plus for addition and subtraction of two complex numbers?
#include<iostream>#include<complex>
int main () {
using namespace std;
complex a {1, 1};
complex b {42, 2};
cout a << " + " << b << " = " << a + b << endl;
cout a << " - " << b << " = " << a - b << endl;
}
How array elements are retrieved?
Array elements are retrieved by specifying the offset of the element you want. Since array elements are a fixed size, you can also retrieve elements using simple pointer arithmetic. In actual fact, this is the underlying mechanism used when you supply an offset.
Consider the following array declaration:
int myArray[5] = { 1, 2, 3, 4, 5 };
Memory is allocated to myArray according to the type of the element specified. The type is int, therefore each element will be exactly 4 bytes in length. The subscript [5] allocates 5 elements to this array, thus 20 bytes (5 x 4 bytes) are allocated in total.
myArray refers to the first address of the memory location where the memory was allocated. It therefore refers to the first element in the array, which is offset 0. To retrieve the value stored at offset 0 we specify the offset as a subscript:
int x = myArray[0];
This effectively copies the value 1 (the value we stored in the first element) and places it in the memory allocated to x.
If we want to copy the last element, the fifth element, we specify the final offset, which is 4.
int y = myArray[4];
As before, this copies the value 5 and places it in the memory allocated to y.
Note that to access the nth element of an array, we specify the offset n-1. Offsets are zero-based, so the last element of an n dimension array is also offset n-1.
If we use pointers, we can better understand the underlying mechanism. myArray refers to the starting address of the entire array, so we can dereference the array by allocating a pointer to this memory location.
int * p = myArray;
This copies the address of myArray and stores it in the memory allocated to p. Therefore p points at the first element in the the array and we can retrieve the value of that element by using the indirection operator.
int z = *p;
This is the same as saying z = myArray[0].
To access the next element (found at offset 1), we simply increment the pointer's value by 1.
++p;
Note that if the value in p was originally the memory location 0x00123456, it is easy to assume it must now be 0x00123457 -- a difference of 1 byte. But p was declared as a pointer to int, so we actually increment the memory address by 4 bytes. So, p now stores the address of myArray[1].
So when we retrieve the element myArray[1], what we're really doing is accessing the value stored 1 x 4 bytes away (offset) from the memory location referred to by myArray. All this is done behind the scenes, but is no different to allocating a pointer to myArray, incrementing it by the specified offset, and finally returning the value through indirection.
We can also use indirection to change the value of an element:
*p = 10;
This is the same as saying:
myArray[1] = 10;
The only problem to be aware of when working with pointers is that your pointer can end up pointing at memory outside of the array. However the same can be said of any pointer. Always make sure you know what you're pointing at before attempting to access the value stored at that location.
Define object oriented data model?
It is based on collection of objects.An object contain values stored in instance variables within the object.An object also contains the bodies of code that operate on object.These bodies of code is called methods.Collection of instance variables and method is called classes.
How do you create a file in c plus plus?
Is it a file or a folder you want to create? Use open/creat/fopen for the former, mkdir for the latter.
Example:
FILE *f;
int rc;
rc= mkdir ("C:\\AA");
if (rc) perror ("Error in mkdir");
f= fopen ("C:\\AA\\MYNEWFILE.TXT", "w");
if (f==NULL) perror ("Error in fopen");
What is the use of assembler in c plus plus?
an assembler is a program,just like a compiler.that processes staaements written in a particular high level language and produces an object code in a low level language (assembly language) that the computer can understand.
What is formal parameter in c?
A variable declared in the header of a method whose initial value is obtained during method invocation (using the actual parameter). So: int method(/*Formal Parameters*/){ //Method Actions return 0; }
What is the need of virtual base classes in c plus plus?
Virtual functions are advantageous in that they allow us to write code in a more generic fashion more easily than would otherwise be possible. More importantly, without virtual functions, polymorphic behaviour would be impossible to achieve.
Consider the following example:
#include<iostream>
struct instrument
{
virtual ~instrument() {}
virtual void play () =0;
};
void foo (instrument& a, instrument& b)
{
a.play();
b.play();
}
struct drum : instrument
{
void play () override { std::cout << "Playing a drum\n"; }
};
struct guitar : instrument
{
void play () override { std::cout << "Playing a guitar\n"; }
};
int main()
{
drum d;
guitar g;
foo(d, g);
}
Output:
Playing a drum
Playing a guitar
There are several things to note about this program. As you know, in C++, all types must be declared before they can be used. However, note that the foo function was defined before the drum and guitar classes were declared and yet it was perfectly able to invoke their specific methods even without a forward declaration. This is made possible because the function knows about the instrument class and that's all it really needs to know about; the instrument class exposes the precise interface required by the foo function.
Note also that the instrument class has a virtual destructor. Unless a class is marked final, a virtual destructor tells us that we may derive a new class from this class. In other words, it tells us that this class can be used as a base class. It is important to note that every class that declares one or more virtual methods MUST also have a virtual destructor. I shall explain why shortly.
The instrument::play() method is a virtual method. The '=0' suffix denotes that the function is pure-virtual. Not all base classes require pure-virtual methods, but in this case we do because the instrument class is a conceptual class rather than a concrete class. That is, it is an abstract object; one we can imagine exists but cannot physically exist in reality. By declaring at least one pure-virtual method, we prevent end-users from constructing objects from the class.
A pure-virtual method may or may not be implemented by its base class, but it must be implemented by its derivatives otherwise they become abstract themselves. By contrast, virtual methods must be implemented in the base class but need not be implemented by the derived classes.
Whenever we declare a method virtual, we guarantee that the most-derived override for that method will always be invoked. Thus when we construct a drum object, its play() method becomes the most-derived override. This is how the foo function was able to invoke drum::play() despite the fact it only knew of the existence of the instrument::play() method. Indeed, the foo function doesn't even know that a refers to a drum any more than b refers to a guitar. All it needs to know is that they are both types of instrument and that is guaranteed by the compiler because both drum and guitar are derived from instrument.
While it is true that every drum is an instrument, it is not true that every instrument is a drum (it could be a guitar). How does the foo function know which of the two overrides to invoke? That's precisely the type of problem virtual functions help to resolve. Every class in a hierarchy has a virtual function table (or v-table) which maps the virtual functions of the base class to the most-derived overrides of those functions. Thus when play() is invoked against an object, the class v-table determines the correct function address according to the actual runtime type of the object.
While the v-table does consume additional memory over and above the size of the class members, the cost is minimal (approximately two words per virtual method). However, sometimes it becomes necessary to "switch on" the runtime type of an object in order to evoke specific behaviour. For instance, suppose our drum object has the following interface:
struct drum : instrument
{
void play () override { std::cout << "Playing a drum\n"; }
void play_rimshot () { std::cout << "Playing a rimshot\n"; }
void play_side_stick () { std::cout << "Playing a sidestick\n"; }
};
The play_rimshot and play_sidestick methods are too specialised to be placed in the instrument class. The instrument class exists to provide a common interface to all instruments but you cannot play a rimshot or sidestick upon a guitar. If these methods were part of the instrument interface then they'd also be part of the guitar interface.
One way to invoke these specific behaviours is to dynamically cast the instrument to a drum. If the cast succeeds, you can definitely invoke these methods. If not, then you cannot. But runtime type information is expensive and is often the result of poor design. It is not that there's anything wrong with having such specialised methods, it is only that accessing them from a generic interface is generally the wrong way to go about invoking them. In this particular case all we really need to do is derive a new class from the drum class to cater for these more specific methods:
struct rimshot : drum
{
void play() override { "Playing a rimshot\n"; }
};
struct sidestick : drum
{
void play() override { "Playing a sidestick\n"; }
};
Even though these classes did not exist when we first wrote our foo function, the function can still cater for them:
rimshot r;
sidestick s;
foo (r, s);
In other words, virtual functions have not only enabled runtime polymorphism without the need for runtime type information, they have also provided some measure of future-proofing our code; we do not need to continually maintain the foo function in order to cater for new behaviours.
What is multilevel inheritance in C plus plus?
Multi-level inheritance involves at least 3 classes, a, b and c, such that a is derived from b, and b is derived from c. c is therefore the least-derived base class, b is an intermediate base class and a is the most-derived class.
What is the difference between base class and derived class in c plus plus?
There is no difference other than that a derived class inherits from a base class. That is, the derived class inherits all the public and protected members of its base class, and is a more specialised form of its base class. Thus both can be treated as if they really were base classes. The derived class can also override the virtual methods of the base class, thus allowing polymorphic behaviour without the need to know the exact type of the derived class.
#include<iostream>
#include<vector>
#include<cassert>
using namespace std;
// Returns a vector of Fibonacci numbers from start to max.
// Sequence A000045 in OEIS if start is 0.
vector<unsigned> fibonacci (const unsigned start, const unsigned max)
{
// Invariants:
if (1<start)
throw std::range_error
("vector<unsigned> fibonacci (const unsigned start, const unsigned max): start < 1");
if (max<start)
throw std::range_error
("vector<unsigned> fibonacci (const unsigned start, const unsigned max): max < start");
// Empty set...
vector<unsigned> fib {};
if (max)
{
// First term...
fib.push_back (start);
if (1<max)
{
// Second term...
fib.push_back (1);
// All remaining terms...
unsigned next = 0;
while ((next = fib.back()+fib[fib.size()-2]) <= max)
fib.push_back (next);
}
}
return fib;
};
// Return true if the given number is prime.
bool is_prime (const unsigned num)
{
if (num<2) return false;
if (!(num%2)) return num==2;
for (unsigned div=3; div<=sqrt(num); div+=2)
if (!(num%div)) return false;
return true;
}
// Displays all prime Fibonacci numbers in range [1:10,000].
int main()
{
const unsigned max=10000;
vector<unsigned> f = fibonacci (1, max);
cout << "Prime Fibonacci numbers in range [1:" << max << "]\n";
for (auto n : f)
if (is_prime (n))
cout << n << ", ";
cout << "\b\b " << endl; // backspace and overwrite trailing comma
}
What are different ways by which you can access public member functions of an object?
You simply access it. That's what public means. You can access a public member from any other class, or even from non class code, so long as the referenced class is in scope to the referencing code. In order to do that, you need to have a reference (directly or indirectly) to the instance of the class you want to reference. This would generally be passed as an argument to the referencing code.