Sample of c plus plus program using a class?
#include <iostream>
class foo{}; // Minimal class declaration.
int main()
{
foo a; // Instantiate an object of the class.
foo b(a); // Instantiate a copy of the class.
return(0);
// Both objects fall from scope at this point.
}
What is an array and how do you use them in c and c plus plus?
#include<iostream>
#include<vector>
int main()
{
std::vector<int> v {1, 4, 8, 15, 23}; // initialise array with 5 elements
v.push_back (42); // add a 6th element
for (auto i : v) std::cout << i << std::endl; // print array elements
}
Conventional base class in c plus plus?
A conventional base class is a class that has a virtual destructor. Virtual destructors are important in most class hierarchies because while we may not always know the exact type of the most-derived class in a hierarchy, we will always know at least one of its base classes. If we destroy that base, it is reasonable to expect the entire object to be destroyed, not just the base, and this can only be achieved with a virtual destructor.
Note that a virtual destructor must be declared in the least-derived class in the hierarchy to ensure correct polymorphic behaviour.
Classes not intended to be used as base classes do not have virtual destructors. This does not mean they cannot be used as base classes, but if you choose to use them as base classes you must be aware of the "unconventional" problems that can arise, particularly when destroying objects through pointers or references to their base classes as will lead to resource leaks.
If you do not wish a class to be used as a base class, then the class should be declared final (since C++11). All other classes can still be used as base classes, however only classes with virtual destructors behave polymorphically.
Typically, if we define at least one virtual function in a class, we should also define a virtual destructor for that class. However, derived classes implicitly inherit virtual destructors from their bases thus the absence of a virtual destructor in a derived class should not be taken to mean the derived class is not intended to be used as a base class; always look at the least-derived class definition to determine if a virtual destructor exists or not.
Along with the final specifier, the overridespecifier was also introduced in C++11. This makes it much easier to document virtual functions and their overrides. That is, we can use the virtual specifier solely to introduce a new virtual function into the class hierarchy, and use the overridespecifier to show that we are explicitly overriding a virtual function rather than simply introducing a new virtual function. We can also use the final specifier to indicate that an individual virtual function cannot be overridden any further:
struct X {
virtual void f ();
virtual ~X ();
};
struct Y : X {
void f () override; // implies X::f() is either virtual or is itself an override
~Y () override; // implies ~X() is virtual or is itself an override
};
struct Z : Y {
void f () override; // implies Y::f() is either virtual or is itself an override
~Z () override; // implies ~Y() is virtual or is itself an override
};
The override and final keywords are only useful if used consistently. However, being part of the language itself means we can now enlist the help of the compiler to catch subtle errors that couldn't be easily caught before:
struct X {
void f () override; // error! X did not inherit an f () thus it cannot be an override!
virtual void g (); // ok
virtual ~X(); // ok
};
struct Y : X {
void g () override final; // ok
~Y () override; // ok
};
struct Z : Y {
void g () override; // error! Y::f() is declared final -- it cannot be overridden!
~Z () override; // ok
};
struct Z2 : Z final {}; // ok
struct Z3 : Z2 {}; // error: Z2 is final -- cannot be used as a base class!
How do you implement queue using stack in c plus plus?
A queue in any language is a singly-linked list structure that permits new data to be inserted only at the end of a list while existing data can only be extracted from the beginning of the list. Queues are also known as a first in, first out (FIFO) structure. Unlike a standard singly-linked list, the list maintains a pointer to the last node as well as the first, in order to insert new data and extract existing data in constant time.
Variations on the queue include the priority queue which permit data to be weighted, such that data with the greatest priority is promoted to the front of the queue, behind any existing data with the same or higher priority, using an insertion sort technique. Insertion is therefore achieved in linear time rather than constant time, however extraction is always in constant time.
Write c plus plus program of any desending number?
The problem with generating Fibonacci numbers is that they get large very fast. They will eventually exceed the range of even 64 bit integers. In C++, one way to solve this issue is to write a dynamic, arbitrary decimal class.
You could create a linked list, where each element represents a digit. The first element is the units digit, the second the tens digit, the third the hundreds digit, and so forth.
Imbed this linked list into a decimal number class, and provide operators to do various math operations such as addition between two instances of the class. When implementing operator+, for instance, iterate through the elements of both classes, adding them, and applying the carries in each step. If need be, invoke the AddDigit method of the linked list to make the r-value larger by one digit.
With this class, implementing construct, destruct, copy, assign, add, and print, you can generate a Fibonacci sequence using the algorithm of keeping three numbers, and iterating each sequence by adding the prior two numbers and then moving numbers around. (More efficient would be to rotate pointers to the three instances, rather than copying them.) As the instances get reused, it would also be helpful if you did not just delete elements, but, rather, allowed for them to be reused by keeping track of how many are in use versus how many are allocated. (Or you could just zero the excees digits. That is your choice, and it is part of your overall design. Keep in mind that you do know how long the list is, by knowing which element is the last element.)
As you develop this class, you will find more uses that involve other operations, such as multiply and divide. You can extend the class as necessary.
The following example demonstrates a very basic implementation that will generate Fibonacci numbers up to a given length (200 digits in the example, but you could easily generate arbitrary length from user input). The program can also be easily adapted to produce the nth Fibonacci. The implementation of the bignum class could be improved enormously by embedding a pointer to std::vector and implementing a move constructor (like a copy constructor, but ownership of the resources is swapped rather than shared). Also, storing one character per element is highly inefficient, it would be far better to store multiple digits in 64-bit elements. However I've kept the class as simple as possible for the purpose of clarity.
#include
#include
class bignum
{
friend std::ostream& operator<<(std::ostream& os, const bignum& n);
public:
bignum(unsigned int n=0);
bignum operator+(const bignum& );
size_t size()const{return(list.size());}
private:
std::list
};
bignum::bignum(unsigned int n)
{
if( n )do
{
unsigned char digit=n%10;
list.push_front( digit );
} while( n/=10 );
}
bignum bignum::operator+(const bignum& n)
{
bignum result;
unsigned char carry=0, digit=0;
std::list
std::list
while( first!=list.rend() second!=n.list.rend() carry )
{
digit=carry;
if( first!=list.rend() ) digit+=*first++;
if( second!=n.list.rend() ) digit+=*second++;
carry=digit/10;
digit%=10;
if( digit first!=list.rend() second!=n.list.rend() carry )
result.list.push_front( digit );
}
return( result );
}
std::ostream& operator<<(std::ostream& os, const bignum& n)
{
if( !n.list.size() )
os<<'0';
else for( std::list
os<<(unsigned int)*it;
return( os );
}
int main()
{
bignum* num1 = new bignum(0); std::cout<<*num1< bignum* num2 = new bignum(1); std::cout<<*num2< // generate the Fibonacci sequence up to a length of 200 digits while(num2->size()<200) { bignum* num3 = new bignum( *num1+*num2 ); delete(num1); num1 = num2; num2 = num3; std::cout<<*num2< } delete( num2 ); num2 = NULL; delete( num1 ); num1 = NULL; std::cout< }
How do you push and pop stack elements?
algorithm of push
if(top==Max-1)
{
cout<<"\n the stack is full";
}
else
top++;
arr[top]=item;
////////////////////////////////////////
algorithm of pop
if(top==-1)
{
cout<<"\n the stack is empty";
}
else
return arr[top];
top--;
}
Is swallowing semen dangerous if you both have an STD?
There is no risk for disease transmission if you both suffer from the same disease. If you have different diseases, the swallower is probably more at risk from disease transmission than the donor depending, of course, on the method of delivery.
#include<conio.h>
#include<stdio.h>
void main(void)
{
int sell_pr, profit, cost_pr, cost_pr_one_item ;
clrscr();
printf("Please enter the selling price of 15 items:");
scanf("%d", &sell_pr);
printf("Please enter the profit earned on 15 items:");
scanf("%d", &profit);
cost_pr = sell_pr - profit;
cost_pr_one_item = cost_pr/15;
printf("Cost price of one item is %d", cost_pr_one_item);
getch();
}
How does a 'string' type string differ from a c-type string?
A char is a single character. A String is a collection of characters. It may be empty (zero characters), have one character, two character, or many characters - even a fairly long text.
The single quote (') is used to deliniate a character during assignment:
char someChar = 'a';
The double quote (") is used to delineate a string during assignment:
String someString = new String("hello there");
Note that char is a primitive data type in Java, while String is an Object. You CANNOT directly assign a char to a String (or vice versa). There is, however, a Character object that wraps the char primitive type, and Java allows method calls to be made on the char primitive (automagically converting the char to Character before doing so).
i.e. these ALL FAIL:
someString = SomeChar;
someString = new String(someChar);
However, these WILL work:
someString = Character.toString(someChar);
someString = someChar.toString();
Also note that a String is a static memory allocation, while a character's is dynamic. By that, I mean that when a String is created, it is allocated a memory location exactly big enough to fit the assigned string. Any change to that String forces and entirely new memory location to be allocated, the contents of the old String copied in (with the appropriate changes), and the old String object subject to garbage collection. Thus, making changes to a String object are quite inefficient (if you want that kind of behaviour, use StringBuffer instead).
A character is allocated but once; all subsequent changes to a character variable simply overwrite that same memory location, so frequent changes to a character variable incur no real penalty.
What does a statement in c plus plus end with?
A simple statement ends with a semi-colon (';'). A compound statement contains one or more simple statements (with semi-colon terminators) enclosed within opening and closing braces ('{' and '}').
Recursive function to find nth number of the Fibonacci series?
STEP1. Set value of count=1, output=1, T1=0, T2=1
STEP2. Read value of n
STEP3. Print output
STEP4. Calculate
output=T1+T2
STEP5. T1=T2 & T2=output
STEP6. Calculate count= count+1
STEP7. If (count<=n>
go to STEP3
else
go to STEP8
STEP8. End
You could also just plug in n into this formula:
F(n) = [φ^n - (1-φ)^n] / sqrt(5)
φ is about 1.618033989 and is the Golden Ratio
[It's also the limit as n approaches infinity of the nth term in the Fibonacci sequence divided by the (n-1)th term]
Difference between Method overloading and method overriding in C plus plus?
Yes. Any base class method that is declared virtual can be overridden by a derived class. Overriding a method that is not declared virtual can still be called, but will not be called polymorphically. That is, if you call the base class method, the base class method will execute, not the override. To call a non-virtual override you must call it explicitly.
Two example of derived data types in c plus plus?
The fundamental built in data types in C++ are integral (char, short, int, and long) and floating (float, double, and long double1).
The fundamental derived data types in C++ are arrays, functions, pointers, and references.
The composed derivative data types in C++ are classes, structures, and unions.
----------------------------------------------------------
1Microsoft specific ??
Why do you use virtual functions in C plus plus?
Virtual means that decision would be taken at another stage... first base class constructor is called and construction of object cannot be held anonymous. that's y virtual constructors are not possible.
AnswerOne reason is that a constructor cannot be virtual is because it is the constructor's job to fill in the v-table for virtual functions. If a constructor was allowed to be virtual, then you end up with kind of a chicken and egg paradox. In order to call the constructor, the compiler would have to look in the v-table to find where the constructor is located. Unfortunately, it's the constructor's job to place the address of virtual functions (which would include itself) into the v-table. Without RTTI, it would be impossible to resolve which child's constructor to call. In most cases, a virtual helper function that the constructor calls is more then enough.How do you write a c plus plus program to find area of a triangle where base4 and height6?
pi x radius x radius the forula for working out the area of a circle if this is what you're asking.
========================================================
Please give the Proper Answer...
Object oriented design and procedural oriented design?
In object oriented programming main role plays objects and classes, in structure programming all programmes are represented as structures of block's, in procedure programming - that means high level programming languages, which are based on process description (sequence of processes) - all programmes are described like a set of subprogrammes or procedures.
For more information you may search these articles:
http:/en.wikipedia.org/wiki/Object-oriented_programming
http://alarmingdevelopment.org/?p=9
http:/en.wikipedia.org/wiki/Procedural_programming
Is the C Plus Plus language good for making software?
C++ is one of the most flexible programming-languages there is. So, my first answer would be 'Yes'. However the question is, if C++ is the most suited language for the software that you want to make. There may be a alternative, easier language, in wich you can develop your software. Jahewi :-)
HOW can a program that outputs the days of the week using switch statement be created?
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf("enter the value of n");
scanf("%d",&n);
switch(n)
{
case1:printf("monday");
break;
case2:printf("tueday");
break;
case3:printf("wednesday");
break;
case4:printf("thursday");
break;
case5:printf("friday");
break;
case6:printf("saturday");
break;
case7:printf("sunday");
break;
default:printf("invalid number");
}
}
How constructor is different from normal member function?
A constructor differs from a normal member function in three ways:
The common design hypothesis is that a well-designed constructor cannot fail, other than maybe in an irrecoverable way (such as a fatal running out of memory).
The common design practise is that at least the default constructor is declared public.
How operator overloading differ from function overloading?
Function overloading is multiple definition with different signatures(the parameters should be different) for the same function. The parameter list have to be different in each definition. The compiler will not accept if the return type alone is changed.
Operator overloading is defining a function for a particular operator. The operator loading function can not be overloaded through function overloading.
Can you use c plus plus instead of c sharp in aspnet?
No, not directly. But maybe yes indirectly
The code behind languages of a web page in asp.net are either VB.NET or C#.
No, you cannot develop / write codes in C++ in these code-behind
You still can call out to some components written in C++ from these code-behind pages via C# or VB.NET codes
Bubble sort is a sorting algorithm that compares 2 adjacent items at a time, starting from the beginning of a list, and swapping them if they are out of sequence. Each comparison gradually moves the largest item to the end of the list (likened to a bubble making its way to the surface of water). After n*n passes, all the items will be sorted. The big O for a standard bubble sort is therefore O(n*n).
The algorithm can be improved somewhat. Since it is clear that the last item is sorted on each pass, the unsorted set can be reduced by 1 element on each pass. Moreover, since the final swap on each pass indicates that everything from that point on is already sorted, the unsorted set can often be reduced by more than 1 element on each pass. For an already sorted list, the worst case is reduced to O(n), constant time.
For small sets of data, perhaps 10 to 20 items, the bubble sort is reasonably efficient, especially on partially sorted lists. However the insert sort algorithm offers similar or better performance on average. With larger sets, the quick sort algorithm is hard to beat, but is let down by inefficiencies when dealing with partially sorted lists. Hybrid sorts can improve things a little, however, there is no efficient way to check the state of a list to determine the most efficient algorithm to use at any given point.
Explain virtual functions in C plus plus?
A virtual function in C++ is a function that can have multiple definitions.
For example:
If you have a class which contains a virtual function:
class Virtual
{
virtual void makesomething();
};
That function can be implemented when you inherit that class an implement the function. So:
class Inherit : public Virtual
{
//this is the same function, but can be implemented to do something different
void makesomething() { //do something else }
};
C program to swap two variables without using third variable?
you can do it in the following manner
Supposing your two variables are x and y:
int x=3;
int y=5;
x=x+y; [x becomes 8]
y=x-y; [y assumes the original value of x i.e. 3]
x=x-y; [x assumes the original value of y i.e. 5]
or... you can use the unary XOR (exclusive or) operator, '^=' .
Same values, int x=3, y=5
x ^= y; // x becomes 6
y ^= x; // y becomes 5
x ^= y; // x becomes 3.
The second method has more advantages :
- Its assembler operations never use the processor's ALU carry.
- Without use of the aforementioned carry, no overflow will ever occur.
- Performing this with 32-bits values 8-bits processors will be more efficient, in terms of program space AND execution speed.
- You can even use this in Visual Basic an other languages which implements boundaries on values, while the first method is guaranteed to fail when overflows occurs.
In both case, do not EVER try to factorize these 3 lines into two, as the operations order in multiple-operators lines depends on the compiler's way to parse your code.
Thus , typing
x = x ^ y ^x;
y = y ^ x;
Will surely give you garbage.